diff --git a/README.md b/README.md index 0f2cadf..5df0dcc 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.5.7-blue.svg?style=flat-square) +![Version](https://img.shields.io/badge/api%20version-1.6.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.5.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.6.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,7 +33,7 @@ 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 - + ``` diff --git a/docs/examples/account/create-anonymous-session.md b/docs/examples/account/create-anonymous-session.md index 618b003..9a78549 100644 --- a/docs/examples/account/create-anonymous-session.md +++ b/docs/examples/account/create-anonymous-session.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.createAnonymousSession(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-email-password-session.md b/docs/examples/account/create-email-password-session.md index 7bbb30e..517a7c7 100644 --- a/docs/examples/account/create-email-password-session.md +++ b/docs/examples/account/create-email-password-session.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.createEmailPasswordSession( 'password' // password ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-email-token.md b/docs/examples/account/create-email-token.md index 3591fcd..bcc9316 100644 --- a/docs/examples/account/create-email-token.md +++ b/docs/examples/account/create-email-token.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -12,4 +12,4 @@ const result = await account.createEmailToken( false // phrase (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-j-w-t.md b/docs/examples/account/create-j-w-t.md index 467d7ab..e01d8de 100644 --- a/docs/examples/account/create-j-w-t.md +++ b/docs/examples/account/create-j-w-t.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.createJWT(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-magic-u-r-l-token.md b/docs/examples/account/create-magic-u-r-l-token.md index c65b5e5..1559447 100644 --- a/docs/examples/account/create-magic-u-r-l-token.md +++ b/docs/examples/account/create-magic-u-r-l-token.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -13,4 +13,4 @@ const result = await account.createMagicURLToken( false // phrase (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-mfa-authenticator.md b/docs/examples/account/create-mfa-authenticator.md index e367f24..6551d13 100644 --- a/docs/examples/account/create-mfa-authenticator.md +++ b/docs/examples/account/create-mfa-authenticator.md @@ -2,7 +2,7 @@ import { Client, Account, AuthenticatorType } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.createMfaAuthenticator( AuthenticatorType.Totp // type ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-mfa-challenge.md b/docs/examples/account/create-mfa-challenge.md index 48318c7..c620ca2 100644 --- a/docs/examples/account/create-mfa-challenge.md +++ b/docs/examples/account/create-mfa-challenge.md @@ -2,7 +2,7 @@ import { Client, Account, AuthenticationFactor } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.createMfaChallenge( AuthenticationFactor.Email // factor ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-mfa-recovery-codes.md b/docs/examples/account/create-mfa-recovery-codes.md index ef5d35d..5a3f6f2 100644 --- a/docs/examples/account/create-mfa-recovery-codes.md +++ b/docs/examples/account/create-mfa-recovery-codes.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.createMfaRecoveryCodes(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-o-auth2session.md b/docs/examples/account/create-o-auth2session.md index c158e3e..0d797a8 100644 --- a/docs/examples/account/create-o-auth2session.md +++ b/docs/examples/account/create-o-auth2session.md @@ -2,7 +2,7 @@ import { Client, Account, OAuthProvider } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); diff --git a/docs/examples/account/create-o-auth2token.md b/docs/examples/account/create-o-auth2token.md index a4ca049..a8d7300 100644 --- a/docs/examples/account/create-o-auth2token.md +++ b/docs/examples/account/create-o-auth2token.md @@ -2,7 +2,7 @@ import { Client, Account, OAuthProvider } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); diff --git a/docs/examples/account/create-phone-token.md b/docs/examples/account/create-phone-token.md index d67892a..01a5d68 100644 --- a/docs/examples/account/create-phone-token.md +++ b/docs/examples/account/create-phone-token.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.createPhoneToken( '+12065550100' // phone ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-phone-verification.md b/docs/examples/account/create-phone-verification.md index cdb4629..5da89e9 100644 --- a/docs/examples/account/create-phone-verification.md +++ b/docs/examples/account/create-phone-verification.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.createPhoneVerification(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-push-target.md b/docs/examples/account/create-push-target.md index fe6dd99..abbbf42 100644 --- a/docs/examples/account/create-push-target.md +++ b/docs/examples/account/create-push-target.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -12,4 +12,4 @@ const result = await account.createPushTarget( '' // providerId (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-recovery.md b/docs/examples/account/create-recovery.md index d6014cd..4d3ec34 100644 --- a/docs/examples/account/create-recovery.md +++ b/docs/examples/account/create-recovery.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.createRecovery( 'https://example.com' // url ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-session.md b/docs/examples/account/create-session.md index a3ee7cc..fe43a12 100644 --- a/docs/examples/account/create-session.md +++ b/docs/examples/account/create-session.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.createSession( '' // secret ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create-verification.md b/docs/examples/account/create-verification.md index 1757f3c..60bb2d2 100644 --- a/docs/examples/account/create-verification.md +++ b/docs/examples/account/create-verification.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.createVerification( 'https://example.com' // url ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/create.md b/docs/examples/account/create.md index 069ade2..eb4634f 100644 --- a/docs/examples/account/create.md +++ b/docs/examples/account/create.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -13,4 +13,4 @@ const result = await account.create( '' // name (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/delete-identity.md b/docs/examples/account/delete-identity.md index 07558e0..7a6dbae 100644 --- a/docs/examples/account/delete-identity.md +++ b/docs/examples/account/delete-identity.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.deleteIdentity( '' // identityId ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/delete-mfa-authenticator.md b/docs/examples/account/delete-mfa-authenticator.md index 6d38924..44f0065 100644 --- a/docs/examples/account/delete-mfa-authenticator.md +++ b/docs/examples/account/delete-mfa-authenticator.md @@ -2,13 +2,12 @@ import { Client, Account, AuthenticatorType } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.deleteMfaAuthenticator( - AuthenticatorType.Totp, // type - '' // otp + AuthenticatorType.Totp // type ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/delete-push-target.md b/docs/examples/account/delete-push-target.md index a5e7cb3..7b8f505 100644 --- a/docs/examples/account/delete-push-target.md +++ b/docs/examples/account/delete-push-target.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.deletePushTarget( '' // targetId ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/delete-session.md b/docs/examples/account/delete-session.md index 4d5129f..15e91fa 100644 --- a/docs/examples/account/delete-session.md +++ b/docs/examples/account/delete-session.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.deleteSession( '' // sessionId ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/delete-sessions.md b/docs/examples/account/delete-sessions.md index a15d130..71761b2 100644 --- a/docs/examples/account/delete-sessions.md +++ b/docs/examples/account/delete-sessions.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.deleteSessions(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/get-mfa-recovery-codes.md b/docs/examples/account/get-mfa-recovery-codes.md index fe3b7a3..3a8c308 100644 --- a/docs/examples/account/get-mfa-recovery-codes.md +++ b/docs/examples/account/get-mfa-recovery-codes.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.getMfaRecoveryCodes(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/get-prefs.md b/docs/examples/account/get-prefs.md index a658911..749df16 100644 --- a/docs/examples/account/get-prefs.md +++ b/docs/examples/account/get-prefs.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.getPrefs(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/get-session.md b/docs/examples/account/get-session.md index b11278b..6e491f5 100644 --- a/docs/examples/account/get-session.md +++ b/docs/examples/account/get-session.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.getSession( '' // sessionId ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/get.md b/docs/examples/account/get.md index 7c000bb..16498a4 100644 --- a/docs/examples/account/get.md +++ b/docs/examples/account/get.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.get(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/list-identities.md b/docs/examples/account/list-identities.md index 4c627ce..f6febdf 100644 --- a/docs/examples/account/list-identities.md +++ b/docs/examples/account/list-identities.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.listIdentities( [] // queries (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/list-logs.md b/docs/examples/account/list-logs.md index 973e37b..02f1abb 100644 --- a/docs/examples/account/list-logs.md +++ b/docs/examples/account/list-logs.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.listLogs( [] // queries (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/list-mfa-factors.md b/docs/examples/account/list-mfa-factors.md index 2e7a6f1..9a9c0d4 100644 --- a/docs/examples/account/list-mfa-factors.md +++ b/docs/examples/account/list-mfa-factors.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.listMfaFactors(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/list-sessions.md b/docs/examples/account/list-sessions.md index 0220b3a..a42018a 100644 --- a/docs/examples/account/list-sessions.md +++ b/docs/examples/account/list-sessions.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.listSessions(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-email.md b/docs/examples/account/update-email.md index 06fabe0..e15f23c 100644 --- a/docs/examples/account/update-email.md +++ b/docs/examples/account/update-email.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.updateEmail( 'password' // password ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-m-f-a.md b/docs/examples/account/update-m-f-a.md index 4e6bb65..8ac7607 100644 --- a/docs/examples/account/update-m-f-a.md +++ b/docs/examples/account/update-m-f-a.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.updateMFA( false // mfa ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-magic-u-r-l-session.md b/docs/examples/account/update-magic-u-r-l-session.md index 665b9f2..5f268f8 100644 --- a/docs/examples/account/update-magic-u-r-l-session.md +++ b/docs/examples/account/update-magic-u-r-l-session.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.updateMagicURLSession( '' // secret ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-mfa-authenticator.md b/docs/examples/account/update-mfa-authenticator.md index 50bd121..3441946 100644 --- a/docs/examples/account/update-mfa-authenticator.md +++ b/docs/examples/account/update-mfa-authenticator.md @@ -2,7 +2,7 @@ import { Client, Account, AuthenticatorType } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.updateMfaAuthenticator( '' // otp ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-mfa-challenge.md b/docs/examples/account/update-mfa-challenge.md index ca9a85d..6c83570 100644 --- a/docs/examples/account/update-mfa-challenge.md +++ b/docs/examples/account/update-mfa-challenge.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.updateMfaChallenge( '' // otp ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-mfa-recovery-codes.md b/docs/examples/account/update-mfa-recovery-codes.md index 529fbae..dce2d4e 100644 --- a/docs/examples/account/update-mfa-recovery-codes.md +++ b/docs/examples/account/update-mfa-recovery-codes.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.updateMfaRecoveryCodes(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-name.md b/docs/examples/account/update-name.md index ac11894..26258fd 100644 --- a/docs/examples/account/update-name.md +++ b/docs/examples/account/update-name.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.updateName( '' // name ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-password.md b/docs/examples/account/update-password.md index f7c815b..84267c0 100644 --- a/docs/examples/account/update-password.md +++ b/docs/examples/account/update-password.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.updatePassword( 'password' // oldPassword (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-phone-session.md b/docs/examples/account/update-phone-session.md index 1d64eb5..5ab1985 100644 --- a/docs/examples/account/update-phone-session.md +++ b/docs/examples/account/update-phone-session.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.updatePhoneSession( '' // secret ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-phone-verification.md b/docs/examples/account/update-phone-verification.md index 5325169..91cb79d 100644 --- a/docs/examples/account/update-phone-verification.md +++ b/docs/examples/account/update-phone-verification.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.updatePhoneVerification( '' // secret ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-phone.md b/docs/examples/account/update-phone.md index 87779d4..03947e3 100644 --- a/docs/examples/account/update-phone.md +++ b/docs/examples/account/update-phone.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.updatePhone( 'password' // password ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-prefs.md b/docs/examples/account/update-prefs.md index d97cd05..4f3039f 100644 --- a/docs/examples/account/update-prefs.md +++ b/docs/examples/account/update-prefs.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.updatePrefs( {} // prefs ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-push-target.md b/docs/examples/account/update-push-target.md index a8ac97c..4803f6b 100644 --- a/docs/examples/account/update-push-target.md +++ b/docs/examples/account/update-push-target.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.updatePushTarget( '' // identifier ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-recovery.md b/docs/examples/account/update-recovery.md index 90bfb6d..716efd2 100644 --- a/docs/examples/account/update-recovery.md +++ b/docs/examples/account/update-recovery.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -12,4 +12,4 @@ const result = await account.updateRecovery( '' // password ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-session.md b/docs/examples/account/update-session.md index 5f30f17..b437056 100644 --- a/docs/examples/account/update-session.md +++ b/docs/examples/account/update-session.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -10,4 +10,4 @@ const result = await account.updateSession( '' // sessionId ); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-status.md b/docs/examples/account/update-status.md index e67bc78..c4b2c0e 100644 --- a/docs/examples/account/update-status.md +++ b/docs/examples/account/update-status.md @@ -2,10 +2,10 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); const result = await account.updateStatus(); -console.log(response); +console.log(result); diff --git a/docs/examples/account/update-verification.md b/docs/examples/account/update-verification.md index a57fe4b..f928efd 100644 --- a/docs/examples/account/update-verification.md +++ b/docs/examples/account/update-verification.md @@ -2,7 +2,7 @@ import { Client, Account } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const account = new Account(client); @@ -11,4 +11,4 @@ const result = await account.updateVerification( '' // secret ); -console.log(response); +console.log(result); diff --git a/docs/examples/avatars/get-browser.md b/docs/examples/avatars/get-browser.md index 682ba98..3ead6d6 100644 --- a/docs/examples/avatars/get-browser.md +++ b/docs/examples/avatars/get-browser.md @@ -2,7 +2,7 @@ import { Client, Avatars, Browser } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const avatars = new Avatars(client); diff --git a/docs/examples/avatars/get-credit-card.md b/docs/examples/avatars/get-credit-card.md index 68b5337..1391a33 100644 --- a/docs/examples/avatars/get-credit-card.md +++ b/docs/examples/avatars/get-credit-card.md @@ -2,7 +2,7 @@ import { Client, Avatars, CreditCard } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const avatars = new Avatars(client); diff --git a/docs/examples/avatars/get-favicon.md b/docs/examples/avatars/get-favicon.md index 5d5e93b..4da10c5 100644 --- a/docs/examples/avatars/get-favicon.md +++ b/docs/examples/avatars/get-favicon.md @@ -2,7 +2,7 @@ import { Client, Avatars } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const avatars = new Avatars(client); diff --git a/docs/examples/avatars/get-flag.md b/docs/examples/avatars/get-flag.md index e8521c9..3bfe49d 100644 --- a/docs/examples/avatars/get-flag.md +++ b/docs/examples/avatars/get-flag.md @@ -2,7 +2,7 @@ import { Client, Avatars, Flag } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const avatars = new Avatars(client); diff --git a/docs/examples/avatars/get-image.md b/docs/examples/avatars/get-image.md index 8b8fbd9..ef639f6 100644 --- a/docs/examples/avatars/get-image.md +++ b/docs/examples/avatars/get-image.md @@ -2,7 +2,7 @@ import { Client, Avatars } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const avatars = new Avatars(client); diff --git a/docs/examples/avatars/get-initials.md b/docs/examples/avatars/get-initials.md index cc456a4..25d2320 100644 --- a/docs/examples/avatars/get-initials.md +++ b/docs/examples/avatars/get-initials.md @@ -2,7 +2,7 @@ import { Client, Avatars } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const avatars = new Avatars(client); diff --git a/docs/examples/avatars/get-q-r.md b/docs/examples/avatars/get-q-r.md index 5254a56..83344a0 100644 --- a/docs/examples/avatars/get-q-r.md +++ b/docs/examples/avatars/get-q-r.md @@ -2,7 +2,7 @@ import { Client, Avatars } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const avatars = new Avatars(client); diff --git a/docs/examples/databases/create-document.md b/docs/examples/databases/create-document.md index 3a4d53d..45448a8 100644 --- a/docs/examples/databases/create-document.md +++ b/docs/examples/databases/create-document.md @@ -2,7 +2,7 @@ import { Client, Databases } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const databases = new Databases(client); @@ -14,4 +14,4 @@ const result = await databases.createDocument( ["read("any")"] // permissions (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/databases/delete-document.md b/docs/examples/databases/delete-document.md index a08b3c7..623e172 100644 --- a/docs/examples/databases/delete-document.md +++ b/docs/examples/databases/delete-document.md @@ -2,7 +2,7 @@ import { Client, Databases } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const databases = new Databases(client); @@ -12,4 +12,4 @@ const result = await databases.deleteDocument( '' // documentId ); -console.log(response); +console.log(result); diff --git a/docs/examples/databases/get-document.md b/docs/examples/databases/get-document.md index d8fe456..bdf9089 100644 --- a/docs/examples/databases/get-document.md +++ b/docs/examples/databases/get-document.md @@ -2,7 +2,7 @@ import { Client, Databases } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const databases = new Databases(client); @@ -13,4 +13,4 @@ const result = await databases.getDocument( [] // queries (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/databases/list-documents.md b/docs/examples/databases/list-documents.md index 3070b00..1d5e48a 100644 --- a/docs/examples/databases/list-documents.md +++ b/docs/examples/databases/list-documents.md @@ -2,7 +2,7 @@ import { Client, Databases } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const databases = new Databases(client); @@ -12,4 +12,4 @@ const result = await databases.listDocuments( [] // queries (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/databases/update-document.md b/docs/examples/databases/update-document.md index 1daaf01..b7e4d5b 100644 --- a/docs/examples/databases/update-document.md +++ b/docs/examples/databases/update-document.md @@ -2,7 +2,7 @@ import { Client, Databases } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const databases = new Databases(client); @@ -14,4 +14,4 @@ const result = await databases.updateDocument( ["read("any")"] // permissions (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/functions/create-execution.md b/docs/examples/functions/create-execution.md index 4a62462..7de0029 100644 --- a/docs/examples/functions/create-execution.md +++ b/docs/examples/functions/create-execution.md @@ -2,17 +2,18 @@ import { Client, Functions, ExecutionMethod } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const functions = new Functions(client); const result = await functions.createExecution( '', // functionId - '', // body (optional) + Payload.fromJson({ x: "y" }), // body (optional) false, // async (optional) '', // path (optional) ExecutionMethod.GET, // method (optional) - {} // headers (optional) + {}, // headers (optional) + '' // scheduledAt (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/functions/get-execution.md b/docs/examples/functions/get-execution.md index 06f9e48..05e2c3c 100644 --- a/docs/examples/functions/get-execution.md +++ b/docs/examples/functions/get-execution.md @@ -2,7 +2,7 @@ import { Client, Functions } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const functions = new Functions(client); @@ -11,4 +11,4 @@ const result = await functions.getExecution( '' // executionId ); -console.log(response); +console.log(result); diff --git a/docs/examples/functions/list-executions.md b/docs/examples/functions/list-executions.md index f6a1c1f..93a70d9 100644 --- a/docs/examples/functions/list-executions.md +++ b/docs/examples/functions/list-executions.md @@ -2,7 +2,7 @@ import { Client, Functions } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const functions = new Functions(client); @@ -12,4 +12,4 @@ const result = await functions.listExecutions( '' // search (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/graphql/mutation.md b/docs/examples/graphql/mutation.md index ca03455..b875f0e 100644 --- a/docs/examples/graphql/mutation.md +++ b/docs/examples/graphql/mutation.md @@ -2,7 +2,7 @@ import { Client, Graphql } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const graphql = new Graphql(client); @@ -10,4 +10,4 @@ const result = await graphql.mutation( {} // query ); -console.log(response); +console.log(result); diff --git a/docs/examples/graphql/query.md b/docs/examples/graphql/query.md index 305e4c1..c0f925a 100644 --- a/docs/examples/graphql/query.md +++ b/docs/examples/graphql/query.md @@ -2,7 +2,7 @@ import { Client, Graphql } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const graphql = new Graphql(client); @@ -10,4 +10,4 @@ const result = await graphql.query( {} // query ); -console.log(response); +console.log(result); diff --git a/docs/examples/locale/get.md b/docs/examples/locale/get.md index 006f339..f3a46b4 100644 --- a/docs/examples/locale/get.md +++ b/docs/examples/locale/get.md @@ -2,10 +2,10 @@ import { Client, Locale } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const locale = new Locale(client); const result = await locale.get(); -console.log(response); +console.log(result); diff --git a/docs/examples/locale/list-codes.md b/docs/examples/locale/list-codes.md index ca73077..36957e9 100644 --- a/docs/examples/locale/list-codes.md +++ b/docs/examples/locale/list-codes.md @@ -2,10 +2,10 @@ import { Client, Locale } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const locale = new Locale(client); const result = await locale.listCodes(); -console.log(response); +console.log(result); diff --git a/docs/examples/locale/list-continents.md b/docs/examples/locale/list-continents.md index 83e35e2..be3b2fa 100644 --- a/docs/examples/locale/list-continents.md +++ b/docs/examples/locale/list-continents.md @@ -2,10 +2,10 @@ import { Client, Locale } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const locale = new Locale(client); const result = await locale.listContinents(); -console.log(response); +console.log(result); diff --git a/docs/examples/locale/list-countries-e-u.md b/docs/examples/locale/list-countries-e-u.md index 7a18ab1..a3af6ae 100644 --- a/docs/examples/locale/list-countries-e-u.md +++ b/docs/examples/locale/list-countries-e-u.md @@ -2,10 +2,10 @@ import { Client, Locale } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const locale = new Locale(client); const result = await locale.listCountriesEU(); -console.log(response); +console.log(result); diff --git a/docs/examples/locale/list-countries-phones.md b/docs/examples/locale/list-countries-phones.md index 2e0daa1..d6845b7 100644 --- a/docs/examples/locale/list-countries-phones.md +++ b/docs/examples/locale/list-countries-phones.md @@ -2,10 +2,10 @@ import { Client, Locale } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const locale = new Locale(client); const result = await locale.listCountriesPhones(); -console.log(response); +console.log(result); diff --git a/docs/examples/locale/list-countries.md b/docs/examples/locale/list-countries.md index 28ce9cc..defdfec 100644 --- a/docs/examples/locale/list-countries.md +++ b/docs/examples/locale/list-countries.md @@ -2,10 +2,10 @@ import { Client, Locale } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const locale = new Locale(client); const result = await locale.listCountries(); -console.log(response); +console.log(result); diff --git a/docs/examples/locale/list-currencies.md b/docs/examples/locale/list-currencies.md index 9ab5b13..7cbf8b8 100644 --- a/docs/examples/locale/list-currencies.md +++ b/docs/examples/locale/list-currencies.md @@ -2,10 +2,10 @@ import { Client, Locale } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const locale = new Locale(client); const result = await locale.listCurrencies(); -console.log(response); +console.log(result); diff --git a/docs/examples/locale/list-languages.md b/docs/examples/locale/list-languages.md index ea02c7f..4f3f877 100644 --- a/docs/examples/locale/list-languages.md +++ b/docs/examples/locale/list-languages.md @@ -2,10 +2,10 @@ import { Client, Locale } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const locale = new Locale(client); const result = await locale.listLanguages(); -console.log(response); +console.log(result); diff --git a/docs/examples/messaging/create-subscriber.md b/docs/examples/messaging/create-subscriber.md index 6485fe3..1fa1de5 100644 --- a/docs/examples/messaging/create-subscriber.md +++ b/docs/examples/messaging/create-subscriber.md @@ -2,7 +2,7 @@ import { Client, Messaging } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const messaging = new Messaging(client); @@ -12,4 +12,4 @@ const result = await messaging.createSubscriber( '' // targetId ); -console.log(response); +console.log(result); diff --git a/docs/examples/messaging/delete-subscriber.md b/docs/examples/messaging/delete-subscriber.md index 1319c9a..bbed071 100644 --- a/docs/examples/messaging/delete-subscriber.md +++ b/docs/examples/messaging/delete-subscriber.md @@ -2,7 +2,7 @@ import { Client, Messaging } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const messaging = new Messaging(client); @@ -11,4 +11,4 @@ const result = await messaging.deleteSubscriber( '' // subscriberId ); -console.log(response); +console.log(result); diff --git a/docs/examples/storage/create-file.md b/docs/examples/storage/create-file.md index 644fc65..29e7100 100644 --- a/docs/examples/storage/create-file.md +++ b/docs/examples/storage/create-file.md @@ -2,15 +2,15 @@ import { Client, Storage } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const storage = new Storage(client); const result = await storage.createFile( '', // bucketId '', // fileId - document.getElementById('uploader').files[0], // file + Payload.fromFile(document.getElementById('uploader').files[0]), // file ["read("any")"] // permissions (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/storage/delete-file.md b/docs/examples/storage/delete-file.md index aefef46..52cc1d4 100644 --- a/docs/examples/storage/delete-file.md +++ b/docs/examples/storage/delete-file.md @@ -2,7 +2,7 @@ import { Client, Storage } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const storage = new Storage(client); @@ -11,4 +11,4 @@ const result = await storage.deleteFile( '' // fileId ); -console.log(response); +console.log(result); diff --git a/docs/examples/storage/get-file-download.md b/docs/examples/storage/get-file-download.md index 4ec5e63..d37541d 100644 --- a/docs/examples/storage/get-file-download.md +++ b/docs/examples/storage/get-file-download.md @@ -2,7 +2,7 @@ import { Client, Storage } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const storage = new Storage(client); diff --git a/docs/examples/storage/get-file-preview.md b/docs/examples/storage/get-file-preview.md index c674e93..6294173 100644 --- a/docs/examples/storage/get-file-preview.md +++ b/docs/examples/storage/get-file-preview.md @@ -2,7 +2,7 @@ import { Client, Storage, ImageGravity, ImageFormat } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const storage = new Storage(client); diff --git a/docs/examples/storage/get-file-view.md b/docs/examples/storage/get-file-view.md index db16105..9a58250 100644 --- a/docs/examples/storage/get-file-view.md +++ b/docs/examples/storage/get-file-view.md @@ -2,7 +2,7 @@ import { Client, Storage } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const storage = new Storage(client); diff --git a/docs/examples/storage/get-file.md b/docs/examples/storage/get-file.md index e52dc19..36c4b45 100644 --- a/docs/examples/storage/get-file.md +++ b/docs/examples/storage/get-file.md @@ -2,7 +2,7 @@ import { Client, Storage } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const storage = new Storage(client); @@ -11,4 +11,4 @@ const result = await storage.getFile( '' // fileId ); -console.log(response); +console.log(result); diff --git a/docs/examples/storage/list-files.md b/docs/examples/storage/list-files.md index ab5a755..731a76e 100644 --- a/docs/examples/storage/list-files.md +++ b/docs/examples/storage/list-files.md @@ -2,7 +2,7 @@ import { Client, Storage } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const storage = new Storage(client); @@ -12,4 +12,4 @@ const result = await storage.listFiles( '' // search (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/storage/update-file.md b/docs/examples/storage/update-file.md index 8eac864..75aefc1 100644 --- a/docs/examples/storage/update-file.md +++ b/docs/examples/storage/update-file.md @@ -2,7 +2,7 @@ import { Client, Storage } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const storage = new Storage(client); @@ -13,4 +13,4 @@ const result = await storage.updateFile( ["read("any")"] // permissions (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/create-membership.md b/docs/examples/teams/create-membership.md index 9d255ec..3f58585 100644 --- a/docs/examples/teams/create-membership.md +++ b/docs/examples/teams/create-membership.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -16,4 +16,4 @@ const result = await teams.createMembership( '' // name (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/create.md b/docs/examples/teams/create.md index 00ca64d..ffa1414 100644 --- a/docs/examples/teams/create.md +++ b/docs/examples/teams/create.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -12,4 +12,4 @@ const result = await teams.create( [] // roles (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/delete-membership.md b/docs/examples/teams/delete-membership.md index c2045cd..dc87116 100644 --- a/docs/examples/teams/delete-membership.md +++ b/docs/examples/teams/delete-membership.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -11,4 +11,4 @@ const result = await teams.deleteMembership( '' // membershipId ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/delete.md b/docs/examples/teams/delete.md index f6e5cb7..99ce856 100644 --- a/docs/examples/teams/delete.md +++ b/docs/examples/teams/delete.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -10,4 +10,4 @@ const result = await teams.delete( '' // teamId ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/get-membership.md b/docs/examples/teams/get-membership.md index 9871a42..d4abeef 100644 --- a/docs/examples/teams/get-membership.md +++ b/docs/examples/teams/get-membership.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -11,4 +11,4 @@ const result = await teams.getMembership( '' // membershipId ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/get-prefs.md b/docs/examples/teams/get-prefs.md index a3d036b..b5b3d12 100644 --- a/docs/examples/teams/get-prefs.md +++ b/docs/examples/teams/get-prefs.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -10,4 +10,4 @@ const result = await teams.getPrefs( '' // teamId ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/get.md b/docs/examples/teams/get.md index f54180f..8306cc5 100644 --- a/docs/examples/teams/get.md +++ b/docs/examples/teams/get.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -10,4 +10,4 @@ const result = await teams.get( '' // teamId ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/list-memberships.md b/docs/examples/teams/list-memberships.md index 436a79b..b1c0681 100644 --- a/docs/examples/teams/list-memberships.md +++ b/docs/examples/teams/list-memberships.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -12,4 +12,4 @@ const result = await teams.listMemberships( '' // search (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/list.md b/docs/examples/teams/list.md index 2376863..0d000e9 100644 --- a/docs/examples/teams/list.md +++ b/docs/examples/teams/list.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -11,4 +11,4 @@ const result = await teams.list( '' // search (optional) ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/update-membership-status.md b/docs/examples/teams/update-membership-status.md index 2e240fa..dd32bbb 100644 --- a/docs/examples/teams/update-membership-status.md +++ b/docs/examples/teams/update-membership-status.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -13,4 +13,4 @@ const result = await teams.updateMembershipStatus( '' // secret ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/update-membership.md b/docs/examples/teams/update-membership.md index dc55d04..ae7fb9a 100644 --- a/docs/examples/teams/update-membership.md +++ b/docs/examples/teams/update-membership.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -12,4 +12,4 @@ const result = await teams.updateMembership( [] // roles ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/update-name.md b/docs/examples/teams/update-name.md index c000401..553c77d 100644 --- a/docs/examples/teams/update-name.md +++ b/docs/examples/teams/update-name.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -11,4 +11,4 @@ const result = await teams.updateName( '' // name ); -console.log(response); +console.log(result); diff --git a/docs/examples/teams/update-prefs.md b/docs/examples/teams/update-prefs.md index e0fbb76..55b273b 100644 --- a/docs/examples/teams/update-prefs.md +++ b/docs/examples/teams/update-prefs.md @@ -2,7 +2,7 @@ import { Client, Teams } from "appwrite"; const client = new Client() .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint - .setProject('5df5acd0d48c2'); // Your project ID + .setProject(''); // Your project ID const teams = new Teams(client); @@ -11,4 +11,4 @@ const result = await teams.updatePrefs( {} // prefs ); -console.log(response); +console.log(result); diff --git a/package.json b/package.json index f124921..3141cde 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": "15.0.0", + "version": "17.0.0-rc1", "license": "BSD-3-Clause", "main": "dist/cjs/sdk.js", "exports": { @@ -26,7 +26,7 @@ }, "devDependencies": { "@rollup/plugin-typescript": "8.3.2", - "playwright": "1.15.0", + "playwright": "1.46.0", "rollup": "2.75.4", "serve-handler": "6.1.0", "tslib": "2.4.0", diff --git a/src/client.ts b/src/client.ts index fb91de0..cb6eb91 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,83 +1,276 @@ import { Models } from './models'; -import { Service } from './service'; +import { Payload } from './payload'; +import { MultipartParser } from './multipart'; -type Payload = { +/** + * Payload type representing a key-value pair with string keys and any values. + */ +type Params = { [key: string]: any; } +/** + * Headers type representing a key-value pair with string keys and string values. + */ type Headers = { [key: string]: string; } +/** + * Realtime response structure with different types. + */ type RealtimeResponse = { + /** + * Type of the response: 'error', 'event', 'connected', or 'response'. + */ type: 'error' | 'event' | 'connected' | 'response'; + + /** + * Data associated with the response based on the response type. + */ data: RealtimeResponseAuthenticated | RealtimeResponseConnected | RealtimeResponseError | RealtimeResponseEvent; } +/** + * Realtime request structure for authentication. + */ type RealtimeRequest = { + /** + * Type of the request: 'authentication'. + */ type: 'authentication'; + + /** + * Data required for authentication. + */ data: RealtimeRequestAuthenticate; } -export type RealtimeResponseEvent = { +/** + * Realtime event response structure with generic payload type. + */ +type RealtimeResponseEvent = { + /** + * List of event names associated with the response. + */ events: string[]; + + /** + * List of channel names associated with the response. + */ channels: string[]; + + /** + * Timestamp indicating the time of the event. + */ timestamp: number; + + /** + * Payload containing event-specific data. + */ payload: T; } +/** + * Realtime response structure for errors. + */ type RealtimeResponseError = { + /** + * Numeric error code indicating the type of error. + */ code: number; + + /** + * Error message describing the encountered error. + */ message: string; } +/** + * Realtime response structure for a successful connection. + */ type RealtimeResponseConnected = { + /** + * List of channels the user is connected to. + */ channels: string[]; + + /** + * User object representing the connected user (optional). + */ user?: object; } +/** + * Realtime response structure for authenticated connections. + */ type RealtimeResponseAuthenticated = { + /** + * Destination channel for the response. + */ to: string; + + /** + * Boolean indicating the success of the authentication process. + */ success: boolean; + + /** + * User object representing the authenticated user. + */ user: object; } +/** + * Realtime request structure for authentication. + */ type RealtimeRequestAuthenticate = { + /** + * Session identifier for authentication. + */ session: string; } +/** + * Realtime interface representing the structure of a realtime communication object. + */ type Realtime = { + /** + * WebSocket instance for realtime communication. + */ socket?: WebSocket; + + /** + * Timeout duration for communication operations. + */ timeout?: number; + + /** + * URL for establishing the WebSocket connection. + */ url?: string; + + /** + * Last received message from the realtime server. + */ lastMessage?: RealtimeResponse; + + /** + * Set of channel names the client is subscribed to. + */ channels: Set; + + /** + * Map of subscriptions containing channel names and corresponding callback functions. + */ subscriptions: Map) => void }>; + + /** + * Counter for managing subscriptions. + */ subscriptionsCounter: number; + + /** + * Boolean indicating whether automatic reconnection is enabled. + */ reconnect: boolean; + + /** + * Number of reconnection attempts made. + */ reconnectAttempts: number; + + /** + * Function to get the timeout duration for communication operations. + */ getTimeout: () => number; + + /** + * Function to establish a WebSocket connection. + */ connect: () => void; + + /** + * Function to create a new WebSocket instance. + */ createSocket: () => void; + + /** + * Function to clean up resources associated with specified channels. + * + * @param {string[]} channels - List of channel names to clean up. + */ cleanUp: (channels: string[]) => void; + + /** + * Function to handle incoming messages from the WebSocket connection. + * + * @param {MessageEvent} event - Event containing the received message. + */ onMessage: (event: MessageEvent) => void; } -export type UploadProgress = { +/** + * Type representing upload progress information. + */ +type UploadProgress = { + /** + * Identifier for the upload progress. + */ $id: string; + + /** + * Current progress of the upload (in percentage). + */ progress: number; + + /** + * Total size uploaded (in bytes) during the upload process. + */ sizeUploaded: number; + + /** + * Total number of chunks that need to be uploaded. + */ chunksTotal: number; + + /** + * Number of chunks that have been successfully uploaded. + */ chunksUploaded: number; } +/** + * Exception thrown by the package + */ class AppwriteException extends Error { + /** + * The error code associated with the exception. + */ code: number; + + /** + * The response string associated with the exception. + */ response: string; + + /** + * Error type. + * See [Error Types](https://appwrite.io/docs/response-codes#errorTypes) for more information. + */ type: string; + + /** + * Initializes a Appwrite Exception. + * + * @param {string} message - The error message. + * @param {number} code - The error code. Default is 0. + * @param {string} type - The error type. Default is an empty string. + * @param {string} response - The response string. Default is an empty string. + */ constructor(message: string, code: number = 0, type: string = '', response: string = '') { super(message); this.name = 'AppwriteException'; @@ -88,7 +281,15 @@ class AppwriteException extends Error { } } +/** + * Client that handles requests to Appwrite + */ class Client { + static CHUNK_SIZE = 1024 * 1024 * 5; + + /** + * Holds configuration such as project. + */ config = { endpoint: 'https://cloud.appwrite.io/v1', endpointRealtime: '', @@ -97,12 +298,15 @@ class Client { locale: '', session: '', }; + /** + * Custom headers for API requests. + */ headers: Headers = { 'x-sdk-name': 'Web', 'x-sdk-platform': 'client', 'x-sdk-language': 'web', - 'x-sdk-version': '15.0.0', - 'X-Appwrite-Response-Format': '1.5.0', + 'x-sdk-version': '17.0.0-rc1', + 'X-Appwrite-Response-Format': '1.6.0', }; /** @@ -148,7 +352,6 @@ class Client { this.config.project = value; return this; } - /** * Set JWT * @@ -163,7 +366,6 @@ class Client { this.config.jwt = value; return this; } - /** * Set Locale * @@ -176,7 +378,6 @@ class Client { this.config.locale = value; return this; } - /** * Set Session * @@ -192,7 +393,6 @@ class Client { return this; } - private realtime: Realtime = { socket: undefined, timeout: undefined, @@ -334,10 +534,10 @@ class Client { /** * Subscribes to Appwrite events and passes you the payload in realtime. - * - * @param {string|string[]} channels + * + * @param {string|string[]} channels * Channel to subscribe - pass a single channel as a string or multiple with an array of strings. - * + * * Possible channels are: * - account * - collections @@ -376,18 +576,11 @@ class Client { } } - async call(method: string, url: URL, headers: Headers = {}, params: Payload = {}): Promise { + async prepareRequest(method: string, url: URL, headers: Headers = {}, params: Params = {}): Promise<{ uri: string, options: RequestInit }> { method = method.toUpperCase(); - headers = Object.assign({}, this.headers, headers); - let options: RequestInit = { - method, - headers, - credentials: 'include' - }; - if (typeof window !== 'undefined' && window.localStorage) { const cookieFallback = window.localStorage.getItem('cookieFallback'); if (cookieFallback) { @@ -395,8 +588,13 @@ class Client { } } + let options: RequestInit = { + method, + headers, + }; + if (method === 'GET') { - for (const [key, value] of Object.entries(Service.flatten(params))) { + for (const [key, value] of Object.entries(Client.flatten(params))) { url.searchParams.append(key, value); } } else { @@ -406,58 +604,135 @@ class Client { break; case 'multipart/form-data': - let formData = new FormData(); - - for (const key in params) { - if (Array.isArray(params[key])) { - params[key].forEach((value: any) => { - formData.append(key + '[]', value); - }) + const formData = new FormData(); + + for (const [name, value] of Object.entries(params)) { + if (value instanceof Payload) { + formData.append(name, await value.toFile(), value.filename); + } else if (Array.isArray(value)) { + for (const nestedValue of value) { + formData.append(`${name}[]`, nestedValue); + } } else { - formData.append(key, params[key]); + formData.append(name, value); } } - + options.body = formData; delete headers['content-type']; + headers['accept'] = 'multipart/form-data'; break; } } - try { - let data = null; - const response = await fetch(url.toString(), options); + return { uri: url.toString(), options }; + } - if (response.headers.get('content-type')?.includes('application/json')) { - data = await response.json(); - } else { - data = { - message: await response.text() - }; + async chunkedUpload(method: string, url: URL, headers: Headers = {}, params: Params = {}, onProgress: (progress: UploadProgress) => void) { + const entry = Object.entries(params).find(([_key, value]) => value instanceof Payload); + if (!entry) { + throw new Error('No payload found in params'); + } + + const [paramName, payload] = entry as [string, Payload]; + + if (payload.size <= Client.CHUNK_SIZE) { + return await this.call(method, url, headers, params); + } + + let start = 0; + let response = null; + + while (start < payload.size) { + const end = Math.min(start + Client.CHUNK_SIZE, payload.size); + + headers['content-range'] = `bytes ${start}-${end-1}/${payload.size}`; + + const buffer = await payload.toBinary(start, end - start); + params[paramName] = Payload.fromBinary(buffer, payload.filename); + + response = await this.call(method, url, headers, params); + + if (onProgress && typeof onProgress === 'function') { + onProgress({ + $id: response.$id, + progress: Math.round((end / payload.size) * 100), + sizeUploaded: end, + chunksTotal: Math.ceil(payload.size / Client.CHUNK_SIZE), + chunksUploaded: Math.ceil(end / Client.CHUNK_SIZE) + }); } - if (400 <= response.status) { - throw new AppwriteException(data?.message, response.status, data?.type, data); + if (response && response.$id) { + headers['x-appwrite-id'] = response.$id; } - const cookieFallback = response.headers.get('X-Fallback-Cookies'); + start = end; + } - if (typeof window !== 'undefined' && window.localStorage && cookieFallback) { - window.console.warn('Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.'); - window.localStorage.setItem('cookieFallback', cookieFallback); - } + return response; + } + + async call(method: string, url: URL, headers: Headers = {}, params: Params = {}, responseType = 'json'): Promise { + const { uri, options } = await this.prepareRequest(method, url, headers, params); + + let data: any = null; + + const response = await fetch(uri, options); + + const warnings = response.headers.get('x-appwrite-warning'); + if (warnings) { + warnings.split(';').forEach((warning: string) => console.warn('Warning: ' + warning)); + } + + if (response.headers.get('content-type')?.includes('application/json')) { + data = await response.json(); + + } else if (response.headers.get('content-type')?.includes('multipart/form-data')) { + const buffer = await response.arrayBuffer(); + const multipart = new MultipartParser(buffer, response.headers.get('content-type')!); + data = multipart.toObject(); + + } else if (responseType === 'arrayBuffer') { + data = await response.arrayBuffer(); + } else { + data = { + message: await response.text() + }; + } - return data; - } catch (e) { - if (e instanceof AppwriteException) { - throw e; + if (400 <= response.status) { + throw new AppwriteException(data?.message, response.status, data?.type, data); + } + + const cookieFallback = response.headers.get('X-Fallback-Cookies'); + + if (typeof window !== 'undefined' && window.localStorage && cookieFallback) { + window.console.warn('Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.'); + window.localStorage.setItem('cookieFallback', cookieFallback); + } + + return data; + } + + static flatten(data: Params, prefix = ''): Params { + let output: Params = {}; + + for (const [key, value] of Object.entries(data)) { + let finalKey = prefix ? prefix + '[' + key +']' : key; + if (Array.isArray(value)) { + output = { ...output, ...Client.flatten(value, finalKey) }; + } else { + output[finalKey] = value; } - throw new AppwriteException((e).message); } + + return output; } } export { Client, AppwriteException }; export { Query } from './query'; -export type { Models, Payload }; +export type { Models, Params, UploadProgress }; +export type { RealtimeResponseEvent }; export type { QueryTypes, QueryTypesList } from './query'; diff --git a/src/id.ts b/src/id.ts index 199f00a..33495cc 100644 --- a/src/id.ts +++ b/src/id.ts @@ -1,6 +1,13 @@ +/** + * Helper class to generate ID strings for resources. + */ export class ID { - // Generate an hex ID based on timestamp - // Recreated from https://www.php.net/manual/en/function.uniqid.php + /** + * Generate an hex ID based on timestamp. + * Recreated from https://www.php.net/manual/en/function.uniqid.php + * + * @returns {string} + */ static #hexTimestamp(): string { const now = new Date(); const sec = Math.floor(now.getTime() / 1000); @@ -11,10 +18,22 @@ export class ID { return hexTimestamp; } + /** + * Uses the provided ID as the ID for the resource. + * + * @param {string} id + * @returns {string} + */ public static custom(id: string): string { return id } + /** + * Have Appwrite generate a unique ID for you. + * + * @param {number} padding. Default is 7. + * @returns {string} + */ public static unique(padding: number = 7): string { // Generate a unique ID with padding to have a longer ID const baseId = ID.#hexTimestamp(); diff --git a/src/index.ts b/src/index.ts index 72a7cc9..b932926 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,10 @@ +/** + * Appwrite Web SDK + * + * This SDK is compatible with Appwrite server version 1.6.x. + * For older versions, please check + * [previous releases](https://github.com/appwrite/sdk-for-web/releases). + */ export { Client, Query, AppwriteException } from './client'; export { Account } from './services/account'; export { Avatars } from './services/avatars'; @@ -8,8 +15,9 @@ export { Locale } from './services/locale'; export { Messaging } from './services/messaging'; export { Storage } from './services/storage'; export { Teams } from './services/teams'; -export type { Models, Payload, RealtimeResponseEvent, UploadProgress } from './client'; +export type { Models, RealtimeResponseEvent, UploadProgress } from './client'; export type { QueryTypes, QueryTypesList } from './query'; +export { Payload } from './payload'; export { Permission } from './permission'; export { Role } from './role'; export { ID } from './id'; diff --git a/src/models.ts b/src/models.ts index cdbd36f..a3066d4 100644 --- a/src/models.ts +++ b/src/models.ts @@ -1,3 +1,8 @@ +import type { Payload } from './payload'; + +/** + * Appwrite Models + */ export namespace Models { /** * Documents List @@ -943,6 +948,10 @@ export namespace Models { * Function execution duration in seconds. */ duration: number; + /** + * The scheduled time for execution. If left empty, execution will be queued immediately. + */ + scheduledAt?: string; } /** * Country diff --git a/src/multipart.ts b/src/multipart.ts new file mode 100644 index 0000000..f534e96 --- /dev/null +++ b/src/multipart.ts @@ -0,0 +1,119 @@ +import { Payload } from "payload"; + +export class MultipartParser { + private buffer: ArrayBuffer; + private boundary: string; + private parts: Record; + + constructor(buffer: ArrayBuffer, contentType: string) { + this.buffer = buffer; + this.boundary = this._extractBoundary(contentType); + this.parts = {}; + this.parse(); + } + + private _extractBoundary(contentType: string) { + const match = contentType.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + if (match) { + return match[1] || match[2]; + } + throw new Error("Boundary not found in Content-Type header"); + } + + private _findBoundaryPositions(view: Uint8Array, boundary: Uint8Array): number[] { + const positions: number[] = []; + for (let i = 0; i < view.length - boundary.length + 1; i++) { + if (view[i] === boundary[0] && view.slice(i, i + boundary.length).every((byte, index) => byte === boundary[index])) { + positions.push(i); + } + } + return positions; + } + + parse() { + const view = new Uint8Array(this.buffer); + const boundaryBytes = new TextEncoder().encode(`--${this.boundary}`); + const boundaryPositions = this._findBoundaryPositions(view, boundaryBytes); + + for (let i = 0; i < boundaryPositions.length - 1; i++) { + const start = boundaryPositions[i] + boundaryBytes.length; + let end = boundaryPositions[i + 1]; + + // Skip initial CRLF after boundary + const partStart = view[start] === 13 && view[start + 1] === 10 ? start + 2 : start; + + // Find the end of headers + const headersEndIndex = this._findSequence(view.slice(partStart, end), [13, 10, 13, 10]); + if (headersEndIndex === -1) continue; + + const headersView = view.slice(partStart, partStart + headersEndIndex); + const contentStart = partStart + headersEndIndex + 4; // +4 to skip \r\n\r\n + + // Trim CRLF before the next boundary + while (end > contentStart && (view[end - 1] === 10 || view[end - 2] === 13)) { + end -= (view[end - 2] === 13) ? 2 : 1; + } + + const contentView = view.slice(contentStart, end); + + const headers = this._parseHeaders(headersView); + const name = this._extractName(headers['content-disposition'] || ''); + + this.parts[name] = { + contents: contentView, + headers: headers + }; + } + } + + private _findSequence(view: Uint8Array, sequence: number[]): number { + for (let i = 0; i <= view.length - sequence.length; i++) { + if (sequence.every((byte, j) => view[i + j] === byte)) { + return i; + } + } + return -1; + } + + private _parseHeaders(headersView: Uint8Array): Record { + const headersText = new TextDecoder().decode(headersView); + const headers: Record = {}; + headersText.split('\r\n').forEach(header => { + const [key, value] = header.split(': '); + if (key && value) { + headers[key.toLowerCase()] = value; + } + }); + return headers; + } + + private _extractName(contentDisposition: string): string { + const nameMatch = contentDisposition.match(/name="([^"]*)"/); + return nameMatch ? nameMatch[1] : `unnamed_part_${Object.keys(this.parts).length}`; + } + + toObject() { + const result: Record = {}; + + for (const [name, part] of Object.entries(this.parts)) { + switch (name) { + case "responseBody": + result[name] = Payload.fromBinary(part.contents); + break; + case "responseHeaders": + result[name] = JSON.parse(new TextDecoder().decode(part.contents)); + break; + case "responseStatusCode": + result[name] = parseInt(new TextDecoder().decode(part.contents), 10); + break; + case "duration": + result[name] = parseFloat(new TextDecoder().decode(part.contents)); + break; + default: + result[name] = new TextDecoder().decode(part.contents); + } + } + + return result; + } +} \ No newline at end of file diff --git a/src/payload.ts b/src/payload.ts new file mode 100644 index 0000000..7200784 --- /dev/null +++ b/src/payload.ts @@ -0,0 +1,48 @@ +export class Payload { + public filename?: string; + public size: number; + + private data: Blob; + + constructor(data: Blob, filename?: string) { + this.data = data; + this.filename = filename; + this.size = data.size; + } + + public async toString(): Promise { + return await this.data.text(); + } + + public async toJson(): Promise { + return JSON.parse(await this.data.text()); + } + + public async toBinary(offset: number = 0, length?: number): Promise { + const end = length ? offset + length : this.size; + return await this.data.slice(offset, end).arrayBuffer(); + } + + public async toFile(filename?: string): Promise { + return this.data; + } + + public static fromFile(file: File | Blob, filename?: string): Payload { + if (file instanceof File && !filename) { + filename = file.name; + } + return new Payload(file, filename); + } + + public static fromString(data: string, filename?: string): Payload { + return new Payload(new Blob([data]), filename); + } + + public static fromJson(data: T, filename?: string): Payload { + return new Payload(new Blob([JSON.stringify(data)]), filename); + } + + public static fromBinary(data: ArrayBuffer, filename?: string): Payload { + return new Payload(new Blob([data]), filename); + } +} \ No newline at end of file diff --git a/src/permission.ts b/src/permission.ts index bfc330a..94d9ced 100644 --- a/src/permission.ts +++ b/src/permission.ts @@ -1,22 +1,57 @@ +/** + * Helper class to generate permission strings for resources. + */ export class Permission { - + /** + * Generate read permission string for the provided role. + * + * @param {string} role + * @returns {string} + */ static read = (role: string): string => { - return `read("${role}")` + return `read("${role}")`; } + /** + * Generate write permission string for the provided role. + * + * This is an alias of update, delete, and possibly create. + * Don't use write in combination with update, delete, or create. + * + * @param {string} role + * @returns {string} + */ static write = (role: string): string => { - return `write("${role}")` + return `write("${role}")`; } + /** + * Generate create permission string for the provided role. + * + * @param {string} role + * @returns {string} + */ static create = (role: string): string => { - return `create("${role}")` + return `create("${role}")`; } + /** + * Generate update permission string for the provided role. + * + * @param {string} role + * @returns {string} + */ static update = (role: string): string => { - return `update("${role}")` + return `update("${role}")`; } + /** + * Generate delete permission string for the provided role. + * + * @param {string} role + * @returns {string} + */ static delete = (role: string): string => { - return `delete("${role}")` + return `delete("${role}")`; } } diff --git a/src/query.ts b/src/query.ts index 229d6c8..acad038 100644 --- a/src/query.ts +++ b/src/query.ts @@ -3,11 +3,21 @@ export type QueryTypesList = string[] | number[] | boolean[] | Query[]; export type QueryTypes = QueryTypesSingle | QueryTypesList; type AttributesTypes = string | string[]; +/** + * Helper class to generate query strings. + */ export class Query { method: string; attribute: AttributesTypes | undefined; values: QueryTypesList | undefined; + /** + * Constructor for Query class. + * + * @param {string} method + * @param {AttributesTypes} attribute + * @param {QueryTypes} values + */ constructor( method: string, attribute?: AttributesTypes, @@ -25,6 +35,11 @@ export class Query { } } + /** + * Convert the query object to a JSON string. + * + * @returns {string} + */ toString(): string { return JSON.stringify({ method: this.method, @@ -33,69 +48,214 @@ export class Query { }); } + /** + * Filter resources where attribute is equal to value. + * + * @param {string} attribute + * @param {QueryTypes} value + * @returns {string} + */ static equal = (attribute: string, value: QueryTypes): string => new Query("equal", attribute, value).toString(); + /** + * Filter resources where attribute is not equal to value. + * + * @param {string} attribute + * @param {QueryTypes} value + * @returns {string} + */ static notEqual = (attribute: string, value: QueryTypes): string => new Query("notEqual", attribute, value).toString(); + /** + * Filter resources where attribute is less than value. + * + * @param {string} attribute + * @param {QueryTypes} value + * @returns {string} + */ static lessThan = (attribute: string, value: QueryTypes): string => new Query("lessThan", attribute, value).toString(); + /** + * Filter resources where attribute is less than or equal to value. + * + * @param {string} attribute + * @param {QueryTypes} value + * @returns {string} + */ static lessThanEqual = (attribute: string, value: QueryTypes): string => new Query("lessThanEqual", attribute, value).toString(); + /** + * Filter resources where attribute is greater than value. + * + * @param {string} attribute + * @param {QueryTypes} value + * @returns {string} + */ static greaterThan = (attribute: string, value: QueryTypes): string => new Query("greaterThan", attribute, value).toString(); + /** + * Filter resources where attribute is greater than or equal to value. + * + * @param {string} attribute + * @param {QueryTypes} value + * @returns {string} + */ static greaterThanEqual = (attribute: string, value: QueryTypes): string => new Query("greaterThanEqual", attribute, value).toString(); + /** + * Filter resources where attribute is null. + * + * @param {string} attribute + * @returns {string} + */ static isNull = (attribute: string): string => new Query("isNull", attribute).toString(); + /** + * Filter resources where attribute is not null. + * + * @param {string} attribute + * @returns {string} + */ static isNotNull = (attribute: string): string => new Query("isNotNull", attribute).toString(); - static between = (attribute: string, start: string | number, end: string | number) => + /** + * Filter resources where attribute is between start and end (inclusive). + * + * @param {string} attribute + * @param {string | number} start + * @param {string | number} end + * @returns {string} + */ + static between = (attribute: string, start: string | number, end: string | number): string => new Query("between", attribute, [start, end] as QueryTypesList).toString(); + /** + * Filter resources where attribute starts with value. + * + * @param {string} attribute + * @param {string} value + * @returns {string} + */ static startsWith = (attribute: string, value: string): string => new Query("startsWith", attribute, value).toString(); + /** + * Filter resources where attribute ends with value. + * + * @param {string} attribute + * @param {string} value + * @returns {string} + */ static endsWith = (attribute: string, value: string): string => new Query("endsWith", attribute, value).toString(); + /** + * Specify which attributes should be returned by the API call. + * + * @param {string[]} attributes + * @returns {string} + */ static select = (attributes: string[]): string => new Query("select", undefined, attributes).toString(); + /** + * Filter resources by searching attribute for value. + * A fulltext index on attribute is required for this query to work. + * + * @param {string} attribute + * @param {string} value + * @returns {string} + */ static search = (attribute: string, value: string): string => new Query("search", attribute, value).toString(); + /** + * Sort results by attribute descending. + * + * @param {string} attribute + * @returns {string} + */ static orderDesc = (attribute: string): string => new Query("orderDesc", attribute).toString(); + /** + * Sort results by attribute ascending. + * + * @param {string} attribute + * @returns {string} + */ static orderAsc = (attribute: string): string => new Query("orderAsc", attribute).toString(); + /** + * Return results after documentId. + * + * @param {string} documentId + * @returns {string} + */ static cursorAfter = (documentId: string): string => new Query("cursorAfter", undefined, documentId).toString(); + /** + * Return results before documentId. + * + * @param {string} documentId + * @returns {string} + */ static cursorBefore = (documentId: string): string => new Query("cursorBefore", undefined, documentId).toString(); + /** + * Return only limit results. + * + * @param {number} limit + * @returns {string} + */ static limit = (limit: number): string => new Query("limit", undefined, limit).toString(); + /** + * Filter resources by skipping the first offset results. + * + * @param {number} offset + * @returns {string} + */ static offset = (offset: number): string => new Query("offset", undefined, offset).toString(); + /** + * Filter resources where attribute contains the specified value. + * + * @param {string} attribute + * @param {string | string[]} value + * @returns {string} + */ static contains = (attribute: string, value: string | string[]): string => new Query("contains", attribute, value).toString(); + /** + * Combine multiple queries using logical OR operator. + * + * @param {string[]} queries + * @returns {string} + */ static or = (queries: string[]) => new Query("or", undefined, queries.map((query) => JSON.parse(query))).toString(); + /** + * Combine multiple queries using logical AND operator. + * + * @param {string[]} queries + * @returns {string} + */ static and = (queries: string[]) => new Query("and", undefined, queries.map((query) => JSON.parse(query))).toString(); } diff --git a/src/service.ts b/src/service.ts deleted file mode 100644 index fe17699..0000000 --- a/src/service.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { Client } from './client'; -import type { Payload } from './client'; - -export class Service { - static CHUNK_SIZE = 5*1024*1024; // 5MB - - client: Client; - - constructor(client: Client) { - this.client = client; - } - - static flatten(data: Payload, prefix = ''): Payload { - let output: Payload = {}; - - for (const [key, value] of Object.entries(data)) { - let finalKey = prefix ? prefix + '[' + key +']' : key; - if (Array.isArray(value)) { - output = { ...output, ...Service.flatten(value, finalKey) }; - } else { - output[finalKey] = value; - } - } - - return output; - } -} \ No newline at end of file diff --git a/src/services/account.ts b/src/services/account.ts index 7e53446..fd88988 100644 --- a/src/services/account.ts +++ b/src/services/account.ts @@ -1,17 +1,16 @@ -import { Service } from '../service'; -import { AppwriteException, Client } from '../client'; +import { Payload } from '../payload'; +import { AppwriteException, Client, type Params, UploadProgress } from '../client'; import type { Models } from '../models'; -import type { UploadProgress, Payload } from '../client'; import { AuthenticatorType } from '../enums/authenticator-type'; import { AuthenticationFactor } from '../enums/authentication-factor'; import { OAuthProvider } from '../enums/o-auth-provider'; -export class Account extends Service { +export class Account { + client: Client; - constructor(client: Client) - { - super(client); - } + constructor(client: Client) { + this.client = client; + } /** * Get account @@ -19,117 +18,113 @@ export class Account extends Service { * Get the currently logged in user. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async get(): Promise> { const apiPath = '/account'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Create 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). + * 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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async create(userId: string, email: string, password: string, name?: string): Promise> { if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } - 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'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof email !== 'undefined') { - payload['email'] = email; + params['email'] = email; } - if (typeof password !== 'undefined') { - payload['password'] = password; + params['password'] = password; } - if (typeof name !== 'undefined') { - payload['name'] = name; + params['name'] = name; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Update email * - * Update currently logged in user account email address. After changing user - * address, the user confirmation status will get reset. A new confirmation - * email is not sent automatically however you can use the send confirmation - * email endpoint again to send the confirmation email. For security measures, - * user password is required to complete this request. - * This endpoint can also be used to convert an anonymous account to a normal - * one, by passing an email address and a new password. - * + * Update currently logged in user account email address. After changing user address, the user confirmation status will get reset. A new confirmation email is not sent automatically however you can use the send confirmation email endpoint again to send the confirmation email. For security measures, user password is required to complete this request. +This endpoint can also be used to convert an anonymous account to a normal one, by passing an email address and a new password. + * * @param {string} email * @param {string} password * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async updateEmail(email: string, password: string): Promise> { 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 = {}; - + const params: Params = {}; if (typeof email !== 'undefined') { - payload['email'] = email; + params['email'] = email; } - if (typeof password !== 'undefined') { - payload['password'] = password; + params['password'] = password; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** * List Identities * @@ -137,22 +132,27 @@ export class Account extends Service { * * @param {string[]} queries * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listIdentities(queries?: string[]): Promise { const apiPath = '/account/identities'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof queries !== 'undefined') { - payload['queries'] = queries; + params['queries'] = queries; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Delete identity * @@ -160,68 +160,79 @@ export class Account extends Service { * * @param {string} identityId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async deleteIdentity(identityId: string): Promise<{}> { if (typeof identityId === 'undefined') { throw new AppwriteException('Missing required parameter: "identityId"'); } - const apiPath = '/account/identities/{identityId}'.replace('{identityId}', identityId); - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('delete', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'delete', + uri, + apiHeaders, + params + ); + } /** * Create JWT * - * Use this endpoint to create a JSON Web Token. You can use the resulting JWT - * to authenticate on behalf of the current user when working with the - * Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes - * from its creation and will be invalid if the user will logout in that time - * frame. + * Use this endpoint to create a JSON Web Token. You can use the resulting JWT to authenticate on behalf of the current user when working with the Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes from its creation and will be invalid if the user will logout in that time frame. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createJWT(): Promise { - const apiPath = '/account/jwt'; - const payload: Payload = {}; - + const apiPath = '/account/jwts'; + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * List logs * - * Get the list of latest security activity logs for the currently logged in - * user. Each log returns user IP address, location and date and time of log. + * Get the list of latest security activity logs for the currently logged in user. Each log returns user IP address, location and date and time of log. * * @param {string[]} queries * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listLogs(queries?: string[]): Promise { const apiPath = '/account/logs'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof queries !== 'undefined') { - payload['queries'] = queries; + params['queries'] = queries; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Update MFA * @@ -229,269 +240,286 @@ export class Account extends Service { * * @param {boolean} mfa * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async updateMFA(mfa: boolean): Promise> { if (typeof mfa === 'undefined') { throw new AppwriteException('Missing required parameter: "mfa"'); } - const apiPath = '/account/mfa'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof mfa !== 'undefined') { - payload['mfa'] = mfa; + params['mfa'] = mfa; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** - * Add Authenticator + * Create Authenticator * - * Add an authenticator app to be used as an MFA factor. Verify the - * authenticator using the [verify - * authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) - * method. + * Add an authenticator app to be used as an MFA factor. Verify the authenticator using the [verify authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator) method. * * @param {AuthenticatorType} type * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createMfaAuthenticator(type: AuthenticatorType): Promise { if (typeof type === 'undefined') { throw new AppwriteException('Missing required parameter: "type"'); } - const apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type); - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Verify Authenticator * - * Verify an authenticator app after adding it using the [add - * authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator) - * method. add + * 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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async updateMfaAuthenticator(type: AuthenticatorType, otp: string): Promise> { 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 = {}; - + const params: Params = {}; if (typeof otp !== 'undefined') { - payload['otp'] = otp; + params['otp'] = otp; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('put', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'put', + uri, + apiHeaders, + params + ); + } /** * Delete Authenticator * * Delete an authenticator for a user by ID. * * @param {AuthenticatorType} type - * @param {string} otp * @throws {AppwriteException} - * @returns {Promise} - */ - async deleteMfaAuthenticator(type: AuthenticatorType, otp: string): Promise<{}> { + * @returns {Promise<{}>} + */ + async deleteMfaAuthenticator(type: AuthenticatorType): Promise<{}> { 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 = {}; + const params: Params = {}; + const uri = new URL(this.client.config.endpoint + apiPath); - if (typeof otp !== 'undefined') { - payload['otp'] = otp; + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('delete', uri, { - 'content-type': 'application/json', - }, payload); + return await this.client.call( + 'delete', + uri, + apiHeaders, + params + ); } - /** - * Create 2FA Challenge + * Create MFA Challenge * - * Begin the process of MFA verification after sign-in. Finish the flow with - * [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) - * method. + * Begin the process of MFA verification after sign-in. Finish the flow with [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge) method. * * @param {AuthenticationFactor} factor * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createMfaChallenge(factor: AuthenticationFactor): Promise { if (typeof factor === 'undefined') { throw new AppwriteException('Missing required parameter: "factor"'); } - const apiPath = '/account/mfa/challenge'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof factor !== 'undefined') { - payload['factor'] = factor; + params['factor'] = factor; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Create MFA Challenge (confirmation) * - * 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. + * 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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async updateMfaChallenge(challengeId: string, otp: string): Promise<{}> { 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 = {}; - + const params: Params = {}; if (typeof challengeId !== 'undefined') { - payload['challengeId'] = challengeId; + params['challengeId'] = challengeId; } - if (typeof otp !== 'undefined') { - payload['otp'] = otp; + params['otp'] = otp; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('put', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'put', + uri, + apiHeaders, + params + ); + } /** * List Factors * * List the factors available on the account to be used as a MFA challange. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listMfaFactors(): Promise { const apiPath = '/account/mfa/factors'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Get MFA Recovery Codes * - * 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. + * 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} - */ + * @returns {Promise} + */ async getMfaRecoveryCodes(): Promise { const apiPath = '/account/mfa/recovery-codes'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Create MFA Recovery Codes * - * Generate recovery codes as backup for MFA flow. It's recommended to - * generate and show then immediately after user successfully adds their - * authehticator. Recovery codes can be used as a MFA verification type in - * [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge) - * method. + * 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} - */ + * @returns {Promise} + */ async createMfaRecoveryCodes(): Promise { const apiPath = '/account/mfa/recovery-codes'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Regenerate MFA Recovery Codes * - * 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. + * 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} - */ + * @returns {Promise} + */ async updateMfaRecoveryCodes(): Promise { const apiPath = '/account/mfa/recovery-codes'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** * Update name * @@ -499,618 +527,626 @@ export class Account extends Service { * * @param {string} name * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async updateName(name: string): Promise> { if (typeof name === 'undefined') { throw new AppwriteException('Missing required parameter: "name"'); } - const apiPath = '/account/name'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof name !== 'undefined') { - payload['name'] = name; + params['name'] = name; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** * Update password * - * Update currently logged in user password. For validation, user is required - * to pass in the new password, and the old password. For users created with - * OAuth, Team Invites and Magic URL, oldPassword is optional. + * Update currently logged in user password. For validation, user is required to pass in the new password, and the old password. For users created with OAuth, Team Invites and Magic URL, oldPassword is optional. * * @param {string} password * @param {string} oldPassword * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async updatePassword(password: string, oldPassword?: string): Promise> { if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } - const apiPath = '/account/password'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof password !== 'undefined') { - payload['password'] = password; + params['password'] = password; } - if (typeof oldPassword !== 'undefined') { - payload['oldPassword'] = oldPassword; + params['oldPassword'] = oldPassword; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** * Update phone * - * 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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async updatePhone(phone: string, password: string): Promise> { 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 = {}; - + const params: Params = {}; if (typeof phone !== 'undefined') { - payload['phone'] = phone; + params['phone'] = phone; } - if (typeof password !== 'undefined') { - payload['password'] = password; + params['password'] = password; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** * Get account preferences * * Get the preferences as a key-value object for the currently logged in user. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async getPrefs(): Promise { const apiPath = '/account/prefs'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Update preferences * - * Update currently logged in user account preferences. The object you pass is - * stored as is, and replaces any previous value. The maximum allowed prefs - * size is 64kB and throws error if exceeded. + * Update currently logged in user account preferences. The object you pass is stored as is, and replaces any previous value. The maximum allowed prefs size is 64kB and throws error if exceeded. * * @param {Partial} prefs * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async updatePrefs(prefs: Partial): Promise> { if (typeof prefs === 'undefined') { throw new AppwriteException('Missing required parameter: "prefs"'); } - const apiPath = '/account/prefs'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof prefs !== 'undefined') { - payload['prefs'] = prefs; + params['prefs'] = prefs; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** * Create password recovery * - * Sends the user an email with a temporary secret key for password reset. - * When the user clicks the confirmation link he is redirected back to your - * app password reset URL with the secret key and email address values - * attached to the URL query string. Use the query string params to submit a - * request to the [PUT - * /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) - * endpoint to complete the process. The verification link sent to the user's - * email address is valid for 1 hour. + * Sends the user an email with a temporary secret key for password reset. When the user clicks the confirmation link he is redirected back to your app password reset URL with the secret key and email address values attached to the URL query string. Use the query string params to submit a request to the [PUT /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery) endpoint to complete the process. The verification link sent to the user's email address is valid for 1 hour. * * @param {string} email * @param {string} url * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createRecovery(email: string, url: string): Promise { 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 = {}; - + const params: Params = {}; if (typeof email !== 'undefined') { - payload['email'] = email; + params['email'] = email; } - if (typeof url !== 'undefined') { - payload['url'] = url; + params['url'] = url; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Create password recovery (confirmation) * - * 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. + * 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 * @param {string} secret * @param {string} password * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updateRecovery(userId: string, secret: string, password: string): Promise { if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } - if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } - if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } - const apiPath = '/account/recovery'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof secret !== 'undefined') { - payload['secret'] = secret; + params['secret'] = secret; } - if (typeof password !== 'undefined') { - payload['password'] = password; + params['password'] = password; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('put', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'put', + uri, + apiHeaders, + params + ); + } /** * List sessions * - * Get the list of active sessions across different devices for the currently - * logged in user. + * Get the list of active sessions across different devices for the currently logged in user. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listSessions(): Promise { const apiPath = '/account/sessions'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Delete sessions * - * Delete all sessions from the user account and remove any sessions cookies - * from the end client. + * Delete all sessions from the user account and remove any sessions cookies from the end client. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async deleteSessions(): Promise<{}> { const apiPath = '/account/sessions'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('delete', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'delete', + uri, + apiHeaders, + params + ); + } /** * Create anonymous session * - * Use this endpoint to allow a new user to register an anonymous account in - * your project. This route will also create a new session for the user. To - * allow the new user to convert an anonymous account to a normal account, you - * need to update its [email and - * password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) - * or create an [OAuth2 - * session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). + * Use this endpoint to allow a new user to register an anonymous account in your project. This route will also create a new session for the user. To allow the new user to convert an anonymous account to a normal account, you need to update its [email and password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail) or create an [OAuth2 session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session). * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createAnonymousSession(): Promise { const apiPath = '/account/sessions/anonymous'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Create email password session * - * 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). + * 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 * @param {string} password * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createEmailPasswordSession(email: string, password: string): Promise { 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 = {}; - + const params: Params = {}; if (typeof email !== 'undefined') { - payload['email'] = email; + params['email'] = email; } - if (typeof password !== 'undefined') { - payload['password'] = password; + params['password'] = password; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Update magic URL session * - * Use this endpoint to create a session from token. Provide the **userId** - * and **secret** parameters from the successful response of authentication - * flows initiated by token creation. For example, magic URL and phone login. + * Use this endpoint to create a session from token. Provide the **userId** and **secret** parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login. * * @param {string} userId * @param {string} secret * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updateMagicURLSession(userId: string, secret: string): Promise { 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 = {}; - + const params: Params = {}; if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof secret !== 'undefined') { - payload['secret'] = secret; + params['secret'] = secret; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('put', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'put', + uri, + apiHeaders, + params + ); + } /** * Create OAuth2 session * - * 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). - * + * 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 * @throws {AppwriteException} - * @returns {void|string} - */ - createOAuth2Session(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): void | URL { + * @returns {Promise} + */ + async createOAuth2Session(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): Promise { if (typeof provider === 'undefined') { throw new AppwriteException('Missing required parameter: "provider"'); } - const apiPath = '/account/sessions/oauth2/{provider}'.replace('{provider}', provider); - const payload: Payload = {}; - + const params: Params = {}; if (typeof success !== 'undefined') { - payload['success'] = success; + params['success'] = success; } - if (typeof failure !== 'undefined') { - payload['failure'] = failure; + params['failure'] = failure; } - if (typeof scopes !== 'undefined') { - payload['scopes'] = scopes; + params['scopes'] = scopes; } - const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; - - for (const [key, value] of Object.entries(Service.flatten(payload))) { + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } + if (typeof window !== 'undefined' && window?.location) { window.location.href = uri.toString(); + return; } else { - return uri; + return uri.toString(); } } - /** * Update phone session * - * Use this endpoint to create a session from token. Provide the **userId** - * and **secret** parameters from the successful response of authentication - * flows initiated by token creation. For example, magic URL and phone login. + * Use this endpoint to create a session from token. Provide the **userId** and **secret** parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login. * * @param {string} userId * @param {string} secret * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updatePhoneSession(userId: string, secret: string): Promise { 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 = {}; - + const params: Params = {}; if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof secret !== 'undefined') { - payload['secret'] = secret; + params['secret'] = secret; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('put', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'put', + uri, + apiHeaders, + params + ); + } /** * Create session * - * Use this endpoint to create a session from token. Provide the **userId** - * and **secret** parameters from the successful response of authentication - * flows initiated by token creation. For example, magic URL and phone login. + * Use this endpoint to create a session from token. Provide the **userId** and **secret** parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login. * * @param {string} userId * @param {string} secret * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createSession(userId: string, secret: string): Promise { 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 = {}; - + const params: Params = {}; if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof secret !== 'undefined') { - payload['secret'] = secret; + params['secret'] = secret; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Get session * - * Use this endpoint to get a logged in user's session using a Session ID. - * Inputting 'current' will return the current session being used. + * Use this endpoint to get a logged in user's session using a Session ID. Inputting 'current' will return the current session being used. * * @param {string} sessionId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async getSession(sessionId: string): Promise { if (typeof sessionId === 'undefined') { throw new AppwriteException('Missing required parameter: "sessionId"'); } - const apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Update session * - * Use this endpoint to extend a session's length. Extending a session is - * useful when session expiry is short. If the session was created using an - * OAuth provider, this endpoint refreshes the access token from the provider. + * Use this endpoint to extend a session's length. Extending a session is useful when session expiry is short. If the session was created using an OAuth provider, this endpoint refreshes the access token from the provider. * * @param {string} sessionId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updateSession(sessionId: string): Promise { if (typeof sessionId === 'undefined') { throw new AppwriteException('Missing required parameter: "sessionId"'); } - const apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** * Delete session * - * Logout the user. Use 'current' as the session ID to logout on this device, - * use a session ID to logout on another device. If you're looking to logout - * the user on all devices, use [Delete - * Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) - * instead. + * Logout the user. Use 'current' as the session ID to logout on this device, use a session ID to logout on another device. If you're looking to logout the user on all devices, use [Delete Sessions](https://appwrite.io/docs/references/cloud/client-web/account#deleteSessions) instead. * * @param {string} sessionId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async deleteSession(sessionId: string): Promise<{}> { if (typeof sessionId === 'undefined') { throw new AppwriteException('Missing required parameter: "sessionId"'); } - const apiPath = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('delete', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'delete', + uri, + apiHeaders, + params + ); + } /** * Update status * - * Block the currently logged in user account. Behind the scene, the user - * record is not deleted but permanently blocked from any access. To - * completely delete a user, use the Users API instead. + * Block the currently logged in user account. Behind the scene, the user record is not deleted but permanently blocked from any access. To completely delete a user, use the Users API instead. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async updateStatus(): Promise> { const apiPath = '/account/status'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** * Create push target * @@ -1119,38 +1155,39 @@ export class Account extends Service { * @param {string} identifier * @param {string} providerId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createPushTarget(targetId: string, identifier: string, providerId?: string): Promise { 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 = {}; - + const params: Params = {}; if (typeof targetId !== 'undefined') { - payload['targetId'] = targetId; + params['targetId'] = targetId; } - if (typeof identifier !== 'undefined') { - payload['identifier'] = identifier; + params['identifier'] = identifier; } - if (typeof providerId !== 'undefined') { - payload['providerId'] = providerId; + params['providerId'] = providerId; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Update push target * @@ -1158,408 +1195,373 @@ export class Account extends Service { * @param {string} targetId * @param {string} identifier * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updatePushTarget(targetId: string, identifier: string): Promise { 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 = {}; - + const params: Params = {}; if (typeof identifier !== 'undefined') { - payload['identifier'] = identifier; + params['identifier'] = identifier; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('put', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'put', + uri, + apiHeaders, + params + ); + } /** * Delete push target * * * @param {string} targetId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async deletePushTarget(targetId: string): Promise<{}> { if (typeof targetId === 'undefined') { throw new AppwriteException('Missing required parameter: "targetId"'); } - const apiPath = '/account/targets/{targetId}/push'.replace('{targetId}', targetId); - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('delete', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'delete', + uri, + apiHeaders, + params + ); + } /** * Create email token (OTP) * - * 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. - * - * 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). + * 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. + +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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createEmailToken(userId: string, email: string, phrase?: boolean): Promise { 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 = {}; - + const params: Params = {}; if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof email !== 'undefined') { - payload['email'] = email; + params['email'] = email; } - if (typeof phrase !== 'undefined') { - payload['phrase'] = phrase; + params['phrase'] = phrase; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Create magic URL token * - * 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. If you are on a mobile device you can leave - * the URL parameter empty, so that the login completion will be handled by - * your Appwrite instance by default. - * - * 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). - * + * 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. If you are on a mobile device you can leave the URL parameter empty, so that the login completion will be handled by your Appwrite instance by default. + +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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createMagicURLToken(userId: string, email: string, url?: string, phrase?: boolean): Promise { 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 = {}; - + const params: Params = {}; if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof email !== 'undefined') { - payload['email'] = email; + params['email'] = email; } - if (typeof url !== 'undefined') { - payload['url'] = url; + params['url'] = url; } - if (typeof phrase !== 'undefined') { - payload['phrase'] = phrase; + params['phrase'] = phrase; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Create OAuth2 token * - * 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). + * 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 * @throws {AppwriteException} - * @returns {void|string} - */ - createOAuth2Token(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): void | URL { + * @returns {Promise} + */ + async createOAuth2Token(provider: OAuthProvider, success?: string, failure?: string, scopes?: string[]): Promise { if (typeof provider === 'undefined') { throw new AppwriteException('Missing required parameter: "provider"'); } - const apiPath = '/account/tokens/oauth2/{provider}'.replace('{provider}', provider); - const payload: Payload = {}; - + const params: Params = {}; if (typeof success !== 'undefined') { - payload['success'] = success; + params['success'] = success; } - if (typeof failure !== 'undefined') { - payload['failure'] = failure; + params['failure'] = failure; } - if (typeof scopes !== 'undefined') { - payload['scopes'] = scopes; + params['scopes'] = scopes; } - const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; - - for (const [key, value] of Object.entries(Service.flatten(payload))) { + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } + if (typeof window !== 'undefined' && window?.location) { window.location.href = uri.toString(); + return; } else { - return uri; + return uri.toString(); } } - /** * Create phone token * - * 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). + * 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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createPhoneToken(userId: string, phone: string): Promise { 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 = {}; - + const params: Params = {}; if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof phone !== 'undefined') { - payload['phone'] = phone; + params['phone'] = phone; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Create email verification * - * 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. - * + * 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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createVerification(url: string): Promise { if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } - const apiPath = '/account/verification'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof url !== 'undefined') { - payload['url'] = url; + params['url'] = url; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Create email verification (confirmation) * - * Use this endpoint to complete the user email verification process. Use both - * the **userId** and **secret** parameters that were attached to your app URL - * to verify the user email ownership. If confirmed this route will return a - * 200 status code. + * Use this endpoint to complete the user email verification process. Use both the **userId** and **secret** parameters that were attached to your app URL to verify the user email ownership. If confirmed this route will return a 200 status code. * * @param {string} userId * @param {string} secret * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updateVerification(userId: string, secret: string): Promise { 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 = {}; - + const params: Params = {}; if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof secret !== 'undefined') { - payload['secret'] = secret; + params['secret'] = secret; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('put', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'put', + uri, + apiHeaders, + params + ); + } /** * Create phone verification * - * 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} - */ + * @returns {Promise} + */ async createPhoneVerification(): Promise { const apiPath = '/account/verification/phone'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** - * Create phone verification (confirmation) + * Update phone verification (confirmation) * - * Use this endpoint to complete the user phone verification process. Use the - * **userId** and **secret** that were sent to your user's phone number to - * verify the user email ownership. If confirmed this route will return a 200 - * status code. + * Use this endpoint to complete the user phone verification process. Use the **userId** and **secret** that were sent to your user's phone number to verify the user email ownership. If confirmed this route will return a 200 status code. * * @param {string} userId * @param {string} secret * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updatePhoneVerification(userId: string, secret: string): Promise { 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 = {}; - + const params: Params = {}; if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof secret !== 'undefined') { - payload['secret'] = secret; + params['secret'] = secret; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('put', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'put', + uri, + apiHeaders, + params + ); } -}; +} diff --git a/src/services/avatars.ts b/src/services/avatars.ts index fae5666..6150e2d 100644 --- a/src/services/avatars.ts +++ b/src/services/avatars.ts @@ -1,355 +1,343 @@ -import { Service } from '../service'; -import { AppwriteException, Client } from '../client'; +import { Payload } from '../payload'; +import { AppwriteException, Client, type Params, UploadProgress } from '../client'; import type { Models } from '../models'; -import type { UploadProgress, Payload } from '../client'; import { Browser } from '../enums/browser'; import { CreditCard } from '../enums/credit-card'; import { Flag } from '../enums/flag'; -export class Avatars extends Service { +export class Avatars { + client: Client; - constructor(client: Client) - { - super(client); - } + constructor(client: Client) { + this.client = client; + } /** * Get browser icon * - * 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. + * 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 * @param {number} width * @param {number} height * @param {number} quality * @throws {AppwriteException} - * @returns {URL} - */ - getBrowser(code: Browser, width?: number, height?: number, quality?: number): URL { + * @returns {string} + */ + getBrowser(code: Browser, width?: number, height?: number, quality?: number): string { if (typeof code === 'undefined') { throw new AppwriteException('Missing required parameter: "code"'); } - const apiPath = '/avatars/browsers/{code}'.replace('{code}', code); - const payload: Payload = {}; - + const params: Params = {}; if (typeof width !== 'undefined') { - payload['width'] = width; + params['width'] = width; } - if (typeof height !== 'undefined') { - payload['height'] = height; + params['height'] = height; } - if (typeof quality !== 'undefined') { - payload['quality'] = quality; + params['quality'] = quality; } - const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { + uri.searchParams.append(key, value); + } + + params['project'] = this.client.config.project; - for (const [key, value] of Object.entries(Service.flatten(payload))) { + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } - return uri; - } + return uri.toString(); + } /** * Get credit card icon * - * 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. - * + * 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 * @param {number} width * @param {number} height * @param {number} quality * @throws {AppwriteException} - * @returns {URL} - */ - getCreditCard(code: CreditCard, width?: number, height?: number, quality?: number): URL { + * @returns {string} + */ + getCreditCard(code: CreditCard, width?: number, height?: number, quality?: number): string { if (typeof code === 'undefined') { throw new AppwriteException('Missing required parameter: "code"'); } - const apiPath = '/avatars/credit-cards/{code}'.replace('{code}', code); - const payload: Payload = {}; - + const params: Params = {}; if (typeof width !== 'undefined') { - payload['width'] = width; + params['width'] = width; } - if (typeof height !== 'undefined') { - payload['height'] = height; + params['height'] = height; } - if (typeof quality !== 'undefined') { - payload['quality'] = quality; + params['quality'] = quality; } - const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { + uri.searchParams.append(key, value); + } + + params['project'] = this.client.config.project; - for (const [key, value] of Object.entries(Service.flatten(payload))) { + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } - return uri; - } + return uri.toString(); + } /** * Get favicon * - * Use this endpoint to fetch the favorite icon (AKA favicon) of any remote - * website URL. - * + * Use this endpoint to fetch the favorite icon (AKA favicon) of any remote website URL. + +This endpoint does not follow HTTP redirects. * * @param {string} url * @throws {AppwriteException} - * @returns {URL} - */ - getFavicon(url: string): URL { + * @returns {string} + */ + getFavicon(url: string): string { if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } - const apiPath = '/avatars/favicon'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof url !== 'undefined') { - payload['url'] = url; + params['url'] = url; } - const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { + uri.searchParams.append(key, value); + } + + params['project'] = this.client.config.project; - for (const [key, value] of Object.entries(Service.flatten(payload))) { + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } - return uri; - } + return uri.toString(); + } /** * Get country flag * - * 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. - * + * 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 * @param {number} width * @param {number} height * @param {number} quality * @throws {AppwriteException} - * @returns {URL} - */ - getFlag(code: Flag, width?: number, height?: number, quality?: number): URL { + * @returns {string} + */ + getFlag(code: Flag, width?: number, height?: number, quality?: number): string { if (typeof code === 'undefined') { throw new AppwriteException('Missing required parameter: "code"'); } - const apiPath = '/avatars/flags/{code}'.replace('{code}', code); - const payload: Payload = {}; - + const params: Params = {}; if (typeof width !== 'undefined') { - payload['width'] = width; + params['width'] = width; } - if (typeof height !== 'undefined') { - payload['height'] = height; + params['height'] = height; } - if (typeof quality !== 'undefined') { - payload['quality'] = quality; + params['quality'] = quality; } - const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { + uri.searchParams.append(key, value); + } + + params['project'] = this.client.config.project; - for (const [key, value] of Object.entries(Service.flatten(payload))) { + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } - return uri; - } + return uri.toString(); + } /** * Get image from URL * - * 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. - * + * 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 * @param {number} width * @param {number} height * @throws {AppwriteException} - * @returns {URL} - */ - getImage(url: string, width?: number, height?: number): URL { + * @returns {string} + */ + getImage(url: string, width?: number, height?: number): string { if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } - const apiPath = '/avatars/image'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof url !== 'undefined') { - payload['url'] = url; + params['url'] = url; } - if (typeof width !== 'undefined') { - payload['width'] = width; + params['width'] = width; } - if (typeof height !== 'undefined') { - payload['height'] = height; + params['height'] = height; } - const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { + uri.searchParams.append(key, value); + } + + params['project'] = this.client.config.project; - for (const [key, value] of Object.entries(Service.flatten(payload))) { + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } - return uri; - } + return uri.toString(); + } /** * Get user initials * - * 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. - * + * Use this endpoint to show your user initials avatar icon on your website or app. By default, this route will try to print your logged-in user name or email initials. You can also overwrite the user name if you pass the 'name' parameter. If no name is given and no user is logged, an empty avatar will be returned. + +You can use the color and background params to change the avatar colors. By default, a random theme will be selected. The random theme will persist for the user's initials when reloading the same theme will always return for the same initials. + +When one dimension is specified and the other is 0, the image is scaled with preserved aspect ratio. If both dimensions are 0, the API provides an image at source quality. If dimensions are not specified, the default size of image returned is 100x100px. + * * @param {string} name * @param {number} width * @param {number} height * @param {string} background * @throws {AppwriteException} - * @returns {URL} - */ - getInitials(name?: string, width?: number, height?: number, background?: string): URL { + * @returns {string} + */ + getInitials(name?: string, width?: number, height?: number, background?: string): string { const apiPath = '/avatars/initials'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof name !== 'undefined') { - payload['name'] = name; + params['name'] = name; } - if (typeof width !== 'undefined') { - payload['width'] = width; + params['width'] = width; } - if (typeof height !== 'undefined') { - payload['height'] = height; + params['height'] = height; } - if (typeof background !== 'undefined') { - payload['background'] = background; + params['background'] = background; } - const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { + uri.searchParams.append(key, value); + } + + params['project'] = this.client.config.project; - for (const [key, value] of Object.entries(Service.flatten(payload))) { + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } - return uri; - } + return uri.toString(); + } /** * Get QR code * - * Converts a given plain text to a QR code image. You can use the query - * parameters to change the size and style of the resulting image. - * + * Converts a given plain text to a QR code image. You can use the query parameters to change the size and style of the resulting image. + * * @param {string} text * @param {number} size * @param {number} margin * @param {boolean} download * @throws {AppwriteException} - * @returns {URL} - */ - getQR(text: string, size?: number, margin?: number, download?: boolean): URL { + * @returns {string} + */ + getQR(text: string, size?: number, margin?: number, download?: boolean): string { if (typeof text === 'undefined') { throw new AppwriteException('Missing required parameter: "text"'); } - const apiPath = '/avatars/qr'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof text !== 'undefined') { - payload['text'] = text; + params['text'] = text; } - if (typeof size !== 'undefined') { - payload['size'] = size; + params['size'] = size; } - if (typeof margin !== 'undefined') { - payload['margin'] = margin; + params['margin'] = margin; } - if (typeof download !== 'undefined') { - payload['download'] = download; + params['download'] = download; } - const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { + uri.searchParams.append(key, value); + } - for (const [key, value] of Object.entries(Service.flatten(payload))) { + params['project'] = this.client.config.project; + + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } - return uri; + + return uri.toString(); } -}; +} diff --git a/src/services/databases.ts b/src/services/databases.ts index d2bbfa1..1b152ec 100644 --- a/src/services/databases.ts +++ b/src/services/databases.ts @@ -1,56 +1,54 @@ -import { Service } from '../service'; -import { AppwriteException, Client } from '../client'; +import { Payload } from '../payload'; +import { AppwriteException, Client, type Params, UploadProgress } from '../client'; import type { Models } from '../models'; -import type { UploadProgress, Payload } from '../client'; -export class Databases extends Service { +export class Databases { + client: Client; - constructor(client: Client) - { - super(client); - } + constructor(client: Client) { + this.client = client; + } /** * List documents * - * Get a list of all the user's documents in a given collection. You can use - * the query params to filter your results. + * Get a list of all the user's documents in a given collection. You can use the query params to filter your results. * * @param {string} databaseId * @param {string} collectionId * @param {string[]} queries * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async listDocuments(databaseId: string, collectionId: string, queries?: string[]): Promise> { 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 = {}; - + const params: Params = {}; if (typeof queries !== 'undefined') { - payload['queries'] = queries; + params['queries'] = queries; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Create document * - * Create a new Document. Before using this route, you should create a new - * collection resource using either a [server - * integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) - * API or directly from your database console. + * Create a new Document. Before using this route, you should create a new collection resource using either a [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection) API or directly from your database console. * * @param {string} databaseId * @param {string} collectionId @@ -58,90 +56,89 @@ export class Databases extends Service { * @param {Omit} data * @param {string[]} permissions * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createDocument(databaseId: string, collectionId: string, documentId: string, data: Omit, permissions?: string[]): Promise { if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } - if (typeof collectionId === 'undefined') { throw new AppwriteException('Missing required parameter: "collectionId"'); } - if (typeof documentId === 'undefined') { throw new AppwriteException('Missing required parameter: "documentId"'); } - if (typeof data === 'undefined') { throw new AppwriteException('Missing required parameter: "data"'); } - const apiPath = '/databases/{databaseId}/collections/{collectionId}/documents'.replace('{databaseId}', databaseId).replace('{collectionId}', collectionId); - const payload: Payload = {}; - + const params: Params = {}; if (typeof documentId !== 'undefined') { - payload['documentId'] = documentId; + params['documentId'] = documentId; } - if (typeof data !== 'undefined') { - payload['data'] = data; + params['data'] = data; } - if (typeof permissions !== 'undefined') { - payload['permissions'] = permissions; + params['permissions'] = permissions; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Get document * - * Get a document by its unique ID. This endpoint response returns a JSON - * object with the document data. + * Get a document by its unique ID. This endpoint response returns a JSON object with the document data. * * @param {string} databaseId * @param {string} collectionId * @param {string} documentId * @param {string[]} queries * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async getDocument(databaseId: string, collectionId: string, documentId: string, queries?: string[]): Promise { if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } - if (typeof collectionId === 'undefined') { throw new AppwriteException('Missing required parameter: "collectionId"'); } - 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 params: Params = {}; if (typeof queries !== 'undefined') { - payload['queries'] = queries; + params['queries'] = queries; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Update document * - * Update a document by its unique ID. Using the patch method you can pass - * only specific fields that will get updated. + * Update a document by its unique ID. Using the patch method you can pass only specific fields that will get updated. * * @param {string} databaseId * @param {string} collectionId @@ -149,38 +146,39 @@ export class Databases extends Service { * @param {Partial>} data * @param {string[]} permissions * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updateDocument(databaseId: string, collectionId: string, documentId: string, data?: Partial>, permissions?: string[]): Promise { if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } - if (typeof collectionId === 'undefined') { throw new AppwriteException('Missing required parameter: "collectionId"'); } - 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 params: Params = {}; if (typeof data !== 'undefined') { - payload['data'] = data; + params['data'] = data; } - if (typeof permissions !== 'undefined') { - payload['permissions'] = permissions; + params['permissions'] = permissions; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** * Delete document * @@ -190,27 +188,31 @@ export class Databases extends Service { * @param {string} collectionId * @param {string} documentId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async deleteDocument(databaseId: string, collectionId: string, documentId: string): Promise<{}> { if (typeof databaseId === 'undefined') { throw new AppwriteException('Missing required parameter: "databaseId"'); } - if (typeof collectionId === 'undefined') { throw new AppwriteException('Missing required parameter: "collectionId"'); } - 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 params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('delete', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'delete', + uri, + apiHeaders, + params + ); } -}; +} diff --git a/src/services/functions.ts b/src/services/functions.ts index 16d55fe..6b2eacb 100644 --- a/src/services/functions.ts +++ b/src/services/functions.ts @@ -1,101 +1,103 @@ -import { Service } from '../service'; -import { AppwriteException, Client } from '../client'; +import { Payload } from '../payload'; +import { AppwriteException, Client, type Params, UploadProgress } from '../client'; import type { Models } from '../models'; -import type { UploadProgress, Payload } from '../client'; import { ExecutionMethod } from '../enums/execution-method'; -export class Functions extends Service { +export class Functions { + client: Client; - constructor(client: Client) - { - super(client); - } + constructor(client: Client) { + this.client = client; + } /** * List executions * - * Get a list of all the current user function execution logs. You can use the - * query params to filter your results. + * Get a list of all the current user function execution logs. You can use the query params to filter your results. * * @param {string} functionId * @param {string[]} queries * @param {string} search * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listExecutions(functionId: string, queries?: string[], search?: string): Promise { if (typeof functionId === 'undefined') { throw new AppwriteException('Missing required parameter: "functionId"'); } - const apiPath = '/functions/{functionId}/executions'.replace('{functionId}', functionId); - const payload: Payload = {}; - + const params: Params = {}; if (typeof queries !== 'undefined') { - payload['queries'] = queries; + params['queries'] = queries; } - if (typeof search !== 'undefined') { - payload['search'] = search; + params['search'] = search; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Create execution * - * Trigger a function execution. The returned object will return you the - * current execution status. You can ping the `Get Execution` endpoint to get - * updates on the current execution status. Once this endpoint is called, your - * function execution process will start asynchronously. + * Trigger a function execution. The returned object will return you the current execution status. You can ping the `Get Execution` endpoint to get updates on the current execution status. Once this endpoint is called, your function execution process will start asynchronously. * * @param {string} functionId - * @param {string} body + * @param {Payload} body * @param {boolean} async * @param {string} xpath * @param {ExecutionMethod} method * @param {object} headers + * @param {string} scheduledAt * @throws {AppwriteException} - * @returns {Promise} - */ - async createExecution(functionId: string, body?: string, async?: boolean, xpath?: string, method?: ExecutionMethod, headers?: object): Promise { + * @returns {Promise} + */ + async createExecution(functionId: string, body?: Payload, async?: boolean, xpath?: string, method?: ExecutionMethod, headers?: object, scheduledAt?: string, onProgress = (progress: UploadProgress) => {}): Promise { if (typeof functionId === 'undefined') { throw new AppwriteException('Missing required parameter: "functionId"'); } - const apiPath = '/functions/{functionId}/executions'.replace('{functionId}', functionId); - const payload: Payload = {}; - + const params: Params = {}; if (typeof body !== 'undefined') { - payload['body'] = body; + params['body'] = body; } - if (typeof async !== 'undefined') { - payload['async'] = async; + params['async'] = async; } - if (typeof xpath !== 'undefined') { - payload['path'] = xpath; + params['path'] = xpath; } - if (typeof method !== 'undefined') { - payload['method'] = method; + params['method'] = method; } - if (typeof headers !== 'undefined') { - payload['headers'] = headers; + params['headers'] = headers; + } + if (typeof scheduledAt !== 'undefined') { + params['scheduledAt'] = scheduledAt; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { - 'content-type': 'application/json', - }, payload); - } + const apiHeaders: { [header: string]: string } = { + 'content-type': 'multipart/form-data', + } + + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Get execution * @@ -104,23 +106,28 @@ export class Functions extends Service { * @param {string} functionId * @param {string} executionId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async getExecution(functionId: string, executionId: string): Promise { 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 params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); } -}; +} diff --git a/src/services/graphql.ts b/src/services/graphql.ts index ca03efb..bb32ea2 100644 --- a/src/services/graphql.ts +++ b/src/services/graphql.ts @@ -1,14 +1,13 @@ -import { Service } from '../service'; -import { AppwriteException, Client } from '../client'; +import { Payload } from '../payload'; +import { AppwriteException, Client, type Params, UploadProgress } from '../client'; import type { Models } from '../models'; -import type { UploadProgress, Payload } from '../client'; -export class Graphql extends Service { +export class Graphql { + client: Client; - constructor(client: Client) - { - super(client); - } + constructor(client: Client) { + this.client = client; + } /** * GraphQL endpoint @@ -17,27 +16,31 @@ export class Graphql extends Service { * * @param {object} query * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async query(query: object): Promise<{}> { if (typeof query === 'undefined') { throw new AppwriteException('Missing required parameter: "query"'); } - const apiPath = '/graphql'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof query !== 'undefined') { - payload['query'] = query; + params['query'] = query; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * GraphQL endpoint * @@ -45,24 +48,29 @@ export class Graphql extends Service { * * @param {object} query * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async mutation(query: object): Promise<{}> { if (typeof query === 'undefined') { throw new AppwriteException('Missing required parameter: "query"'); } - const apiPath = '/graphql/mutation'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof query !== 'undefined') { - payload['query'] = query; + params['query'] = query; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'x-sdk-graphql': 'true', 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); } -}; +} diff --git a/src/services/locale.ts b/src/services/locale.ts index d70b5ed..b9f48a0 100644 --- a/src/services/locale.ts +++ b/src/services/locale.ts @@ -1,169 +1,206 @@ -import { Service } from '../service'; -import { AppwriteException, Client } from '../client'; +import { Payload } from '../payload'; +import { AppwriteException, Client, type Params, UploadProgress } from '../client'; import type { Models } from '../models'; -import type { UploadProgress, Payload } from '../client'; -export class Locale extends Service { +export class Locale { + client: Client; - constructor(client: Client) - { - super(client); - } + constructor(client: Client) { + this.client = client; + } /** * Get user locale * - * Get the current user location based on IP. Returns an object with user - * country code, country name, continent name, continent code, ip address and - * suggested currency. You can use the locale header to get the data in a - * supported language. - * - * ([IP Geolocation by DB-IP](https://db-ip.com)) + * Get the current user location based on IP. Returns an object with user country code, country name, continent name, continent code, ip address and suggested currency. You can use the locale header to get the data in a supported language. + +([IP Geolocation by DB-IP](https://db-ip.com)) * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async get(): Promise { const apiPath = '/locale'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); } - /** * List Locale Codes * - * List of all locale codes in [ISO - * 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + * List of all locale codes in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listCodes(): Promise { const apiPath = '/locale/codes'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); } - /** * List continents * - * List of all continents. You can use the locale header to get the data in a - * supported language. + * List of all continents. You can use the locale header to get the data in a supported language. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listContinents(): Promise { const apiPath = '/locale/continents'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); } - /** * List countries * - * List of all countries. You can use the locale header to get the data in a - * supported language. + * List of all countries. You can use the locale header to get the data in a supported language. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listCountries(): Promise { const apiPath = '/locale/countries'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); } - /** * List EU countries * - * List of all countries that are currently members of the EU. You can use the - * locale header to get the data in a supported language. + * List of all countries that are currently members of the EU. You can use the locale header to get the data in a supported language. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listCountriesEU(): Promise { const apiPath = '/locale/countries/eu'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); } - /** * List countries phone codes * - * List of all countries phone codes. You can use the locale header to get the - * data in a supported language. + * List of all countries phone codes. You can use the locale header to get the data in a supported language. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listCountriesPhones(): Promise { const apiPath = '/locale/countries/phones'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); } - /** * List currencies * - * List of all currencies, including currency symbol, name, plural, and - * decimal digits for all major and minor currencies. You can use the locale - * header to get the data in a supported language. + * List of all currencies, including currency symbol, name, plural, and decimal digits for all major and minor currencies. You can use the locale header to get the data in a supported language. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listCurrencies(): Promise { const apiPath = '/locale/currencies'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); } - /** * List languages * - * List of all languages classified by ISO 639-1 including 2-letter code, name - * in English, and name in the respective language. + * List of all languages classified by ISO 639-1 including 2-letter code, name in English, and name in the respective language. * * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listLanguages(): Promise { const apiPath = '/locale/languages'; - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); } -}; +} diff --git a/src/services/messaging.ts b/src/services/messaging.ts index 16920b2..f897ede 100644 --- a/src/services/messaging.ts +++ b/src/services/messaging.ts @@ -1,14 +1,13 @@ -import { Service } from '../service'; -import { AppwriteException, Client } from '../client'; +import { Payload } from '../payload'; +import { AppwriteException, Client, type Params, UploadProgress } from '../client'; import type { Models } from '../models'; -import type { UploadProgress, Payload } from '../client'; -export class Messaging extends Service { +export class Messaging { + client: Client; - constructor(client: Client) - { - super(client); - } + constructor(client: Client) { + this.client = client; + } /** * Create subscriber @@ -19,38 +18,39 @@ export class Messaging extends Service { * @param {string} subscriberId * @param {string} targetId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createSubscriber(topicId: string, subscriberId: string, targetId: string): Promise { if (typeof topicId === 'undefined') { throw new AppwriteException('Missing required parameter: "topicId"'); } - if (typeof subscriberId === 'undefined') { throw new AppwriteException('Missing required parameter: "subscriberId"'); } - if (typeof targetId === 'undefined') { throw new AppwriteException('Missing required parameter: "targetId"'); } - const apiPath = '/messaging/topics/{topicId}/subscribers'.replace('{topicId}', topicId); - const payload: Payload = {}; - + const params: Params = {}; if (typeof subscriberId !== 'undefined') { - payload['subscriberId'] = subscriberId; + params['subscriberId'] = subscriberId; } - if (typeof targetId !== 'undefined') { - payload['targetId'] = targetId; + params['targetId'] = targetId; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Delete subscriber * @@ -59,23 +59,28 @@ export class Messaging extends Service { * @param {string} topicId * @param {string} subscriberId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async deleteSubscriber(topicId: string, subscriberId: string): Promise<{}> { 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 params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('delete', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'delete', + uri, + apiHeaders, + params + ); } -}; +} diff --git a/src/services/storage.ts b/src/services/storage.ts index 83a51b1..975d59d 100644 --- a/src/services/storage.ts +++ b/src/services/storage.ts @@ -1,301 +1,251 @@ -import { Service } from '../service'; -import { AppwriteException, Client } from '../client'; +import { Payload } from '../payload'; +import { AppwriteException, Client, type Params, UploadProgress } from '../client'; import type { Models } from '../models'; -import type { UploadProgress, Payload } from '../client'; import { ImageGravity } from '../enums/image-gravity'; import { ImageFormat } from '../enums/image-format'; -export class Storage extends Service { +export class Storage { + client: Client; - constructor(client: Client) - { - super(client); - } + constructor(client: Client) { + this.client = client; + } /** * List files * - * Get a list of all the user files. You can use the query params to filter - * your results. + * Get a list of all the user files. You can use the query params to filter your results. * * @param {string} bucketId * @param {string[]} queries * @param {string} search * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listFiles(bucketId: string, queries?: string[], search?: string): Promise { if (typeof bucketId === 'undefined') { throw new AppwriteException('Missing required parameter: "bucketId"'); } - const apiPath = '/storage/buckets/{bucketId}/files'.replace('{bucketId}', bucketId); - const payload: Payload = {}; - + const params: Params = {}; if (typeof queries !== 'undefined') { - payload['queries'] = queries; + params['queries'] = queries; } - if (typeof search !== 'undefined') { - payload['search'] = search; + params['search'] = search; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Create file * - * 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. - * + * Create a new file. Before using this route, you should create a new bucket resource using either a [server integration](https://appwrite.io/docs/server/storage#storageCreateBucket) API or directly from your Appwrite console. + +Larger files should be uploaded using multiple requests with the [content-range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range) header to send a partial request with a maximum supported chunk of `5MB`. The `content-range` header values should always be in bytes. + +When the first request is sent, the server will return the **File** object, and the subsequent part request must include the file's **id** in `x-appwrite-id` header to allow the server to know that the partial upload is for the existing file and not for a new one. + +If you're creating a new file using one of the Appwrite SDKs, all the chunking logic will be managed by the SDK internally. + * * @param {string} bucketId * @param {string} fileId - * @param {File} file + * @param {Payload} file * @param {string[]} permissions * @throws {AppwriteException} - * @returns {Promise} - */ - async createFile(bucketId: string, fileId: string, file: File, permissions?: string[], onProgress = (progress: UploadProgress) => {}): Promise { + * @returns {Promise} + */ + async createFile(bucketId: string, fileId: string, file: Payload, permissions?: string[], onProgress = (progress: UploadProgress) => {}): Promise { if (typeof bucketId === 'undefined') { throw new AppwriteException('Missing required parameter: "bucketId"'); } - if (typeof fileId === 'undefined') { throw new AppwriteException('Missing required parameter: "fileId"'); } - if (typeof file === 'undefined') { throw new AppwriteException('Missing required parameter: "file"'); } - const apiPath = '/storage/buckets/{bucketId}/files'.replace('{bucketId}', bucketId); - const payload: Payload = {}; - + const params: Params = {}; if (typeof fileId !== 'undefined') { - payload['fileId'] = fileId; + params['fileId'] = fileId; } - if (typeof file !== 'undefined') { - payload['file'] = file; + params['file'] = file; } - if (typeof permissions !== 'undefined') { - payload['permissions'] = permissions; + params['permissions'] = permissions; } - const uri = new URL(this.client.config.endpoint + apiPath); - if(!(file instanceof File)) { - throw new AppwriteException('Parameter "file" has to be a File.'); - } - - const size = file.size; - - if (size <= Service.CHUNK_SIZE) { - return await this.client.call('post', uri, { - 'content-type': 'multipart/form-data', - }, payload); - } - const apiHeaders: { [header: string]: string } = { 'content-type': 'multipart/form-data', } - let offset = 0; - let response = undefined; - if(fileId != 'unique()') { - try { - response = await this.client.call('GET', new URL(this.client.config.endpoint + apiPath + '/' + fileId), apiHeaders); - offset = response.chunksUploaded * Service.CHUNK_SIZE; - } catch(e) { - } - } - - while (offset < size) { - let end = Math.min(offset + Service.CHUNK_SIZE - 1, size - 1); - - apiHeaders['content-range'] = 'bytes ' + offset + '-' + end + '/' + size; - if (response && response.$id) { - apiHeaders['x-appwrite-id'] = response.$id; - } - - const chunk = file.slice(offset, end + 1); - payload['file'] = new File([chunk], file.name); - response = await this.client.call('post', uri, apiHeaders, payload); - - if (onProgress) { - onProgress({ - $id: response.$id, - progress: (offset / size) * 100, - sizeUploaded: offset, - chunksTotal: response.chunksTotal, - chunksUploaded: response.chunksUploaded - }); - } - offset += Service.CHUNK_SIZE; - } - return response; + return await this.client.chunkedUpload( + 'post', + uri, + apiHeaders, + params, + onProgress + ); } - /** * Get file * - * Get a file by its unique ID. This endpoint response returns a JSON object - * with the file metadata. + * Get a file by its unique ID. This endpoint response returns a JSON object with the file metadata. * * @param {string} bucketId * @param {string} fileId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async getFile(bucketId: string, fileId: string): Promise { 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 params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Update file * - * Update a file by its unique ID. Only users with write permissions have - * access to update this resource. + * Update a file by its unique ID. Only users with write permissions have access to update this resource. * * @param {string} bucketId * @param {string} fileId * @param {string} name * @param {string[]} permissions * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updateFile(bucketId: string, fileId: string, name?: string, permissions?: string[]): Promise { 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 params: Params = {}; if (typeof name !== 'undefined') { - payload['name'] = name; + params['name'] = name; } - if (typeof permissions !== 'undefined') { - payload['permissions'] = permissions; + params['permissions'] = permissions; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('put', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'put', + uri, + apiHeaders, + params + ); + } /** * Delete File * - * Delete a file by its unique ID. Only users with write permissions have - * access to delete this resource. + * Delete a file by its unique ID. Only users with write permissions have access to delete this resource. * * @param {string} bucketId * @param {string} fileId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async deleteFile(bucketId: string, fileId: string): Promise<{}> { 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 params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('delete', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'delete', + uri, + apiHeaders, + params + ); + } /** * Get file for download * - * 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 * @throws {AppwriteException} - * @returns {URL} - */ - getFileDownload(bucketId: string, fileId: string): URL { + * @returns {string} + */ + getFileDownload(bucketId: string, fileId: string): string { 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 = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { + uri.searchParams.append(key, value); + } + + params['project'] = this.client.config.project; - for (const [key, value] of Object.entries(Service.flatten(payload))) { + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } - return uri; - } + return uri.toString(); + } /** * Get file preview * - * Get a file preview image. Currently, this method supports preview for image - * files (jpg, png, and gif), other supported formats, like pdf, docs, slides, - * and spreadsheets, will return the file icon image. You can also pass query - * string arguments for cutting and resizing your preview image. Preview is - * supported only for image files smaller than 10MB. + * Get a file preview image. Currently, this method supports preview for image files (jpg, png, and gif), other supported formats, like pdf, docs, slides, and spreadsheets, will return the file icon image. You can also pass query string arguments for cutting and resizing your preview image. Preview is supported only for image files smaller than 10MB. * * @param {string} bucketId * @param {string} fileId @@ -311,105 +261,103 @@ export class Storage extends Service { * @param {string} background * @param {ImageFormat} output * @throws {AppwriteException} - * @returns {URL} - */ - 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): URL { + * @returns {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): string { 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 = {}; - + const params: Params = {}; if (typeof width !== 'undefined') { - payload['width'] = width; + params['width'] = width; } - if (typeof height !== 'undefined') { - payload['height'] = height; + params['height'] = height; } - if (typeof gravity !== 'undefined') { - payload['gravity'] = gravity; + params['gravity'] = gravity; } - if (typeof quality !== 'undefined') { - payload['quality'] = quality; + params['quality'] = quality; } - if (typeof borderWidth !== 'undefined') { - payload['borderWidth'] = borderWidth; + params['borderWidth'] = borderWidth; } - if (typeof borderColor !== 'undefined') { - payload['borderColor'] = borderColor; + params['borderColor'] = borderColor; } - if (typeof borderRadius !== 'undefined') { - payload['borderRadius'] = borderRadius; + params['borderRadius'] = borderRadius; } - if (typeof opacity !== 'undefined') { - payload['opacity'] = opacity; + params['opacity'] = opacity; } - if (typeof rotation !== 'undefined') { - payload['rotation'] = rotation; + params['rotation'] = rotation; } - if (typeof background !== 'undefined') { - payload['background'] = background; + params['background'] = background; } - if (typeof output !== 'undefined') { - payload['output'] = output; + params['output'] = output; } - const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { + uri.searchParams.append(key, value); + } + + params['project'] = this.client.config.project; - for (const [key, value] of Object.entries(Service.flatten(payload))) { + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } - return uri; - } + return uri.toString(); + } /** * Get file for view * - * Get a file content by its unique ID. This endpoint is similar to the - * download method but returns with no 'Content-Disposition: attachment' - * header. + * Get a file content by its unique ID. This endpoint is similar to the download method but returns with no 'Content-Disposition: attachment' header. * * @param {string} bucketId * @param {string} fileId * @throws {AppwriteException} - * @returns {URL} - */ - getFileView(bucketId: string, fileId: string): URL { + * @returns {string} + */ + getFileView(bucketId: string, fileId: string): string { 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 = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - payload['project'] = this.client.config.project; + const apiHeaders: { [header: string]: string } = { + 'content-type': 'application/json', + } + params['project'] = this.client.config.project; + for (const [key, value] of Object.entries(Client.flatten(params))) { + uri.searchParams.append(key, value); + } + + params['project'] = this.client.config.project; - for (const [key, value] of Object.entries(Service.flatten(payload))) { + for (const [key, value] of Object.entries(Client.flatten(params))) { uri.searchParams.append(key, value); } - return uri; + + return uri.toString(); } -}; +} diff --git a/src/services/teams.ts b/src/services/teams.ts index 4c47f3d..a348bad 100644 --- a/src/services/teams.ts +++ b/src/services/teams.ts @@ -1,87 +1,88 @@ -import { Service } from '../service'; -import { AppwriteException, Client } from '../client'; +import { Payload } from '../payload'; +import { AppwriteException, Client, type Params, UploadProgress } from '../client'; import type { Models } from '../models'; -import type { UploadProgress, Payload } from '../client'; -export class Teams extends Service { +export class Teams { + client: Client; - constructor(client: Client) - { - super(client); - } + constructor(client: Client) { + this.client = client; + } /** * List 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. + * 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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async list(queries?: string[], search?: string): Promise> { const apiPath = '/teams'; - const payload: Payload = {}; - + const params: Params = {}; if (typeof queries !== 'undefined') { - payload['queries'] = queries; + params['queries'] = queries; } - if (typeof search !== 'undefined') { - payload['search'] = search; + params['search'] = search; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Create team * - * Create a new team. The user who creates the team will automatically be - * assigned as the owner of the team. Only the users with the owner role can - * invite new members, add new owners and delete or update the team. + * 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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async create(teamId: string, name: string, roles?: string[]): Promise> { 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 = {}; - + const params: Params = {}; if (typeof teamId !== 'undefined') { - payload['teamId'] = teamId; + params['teamId'] = teamId; } - if (typeof name !== 'undefined') { - payload['name'] = name; + params['name'] = name; } - if (typeof roles !== 'undefined') { - payload['roles'] = roles; + params['roles'] = roles; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Get team * @@ -89,136 +90,137 @@ export class Teams extends Service { * * @param {string} teamId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async get(teamId: string): Promise> { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } - const apiPath = '/teams/{teamId}'.replace('{teamId}', teamId); - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Update name * - * Update the team's name by its unique ID. + * Update the team's name by its unique ID. * * @param {string} teamId * @param {string} name * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise>} + */ async updateName(teamId: string, name: string): Promise> { 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 = {}; - + const params: Params = {}; if (typeof name !== 'undefined') { - payload['name'] = name; + params['name'] = name; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('put', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'put', + uri, + apiHeaders, + params + ); + } /** * Delete team * - * Delete a team using its ID. Only team members with the owner role can - * delete the team. + * Delete a team using its ID. Only team members with the owner role can delete the team. * * @param {string} teamId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async delete(teamId: string): Promise<{}> { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } - const apiPath = '/teams/{teamId}'.replace('{teamId}', teamId); - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('delete', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'delete', + uri, + apiHeaders, + params + ); + } /** * List team memberships * - * Use this endpoint to list a team's members using the team's ID. All team - * members have read access to this endpoint. + * Use this endpoint to list a team's members using the team's ID. All team members have read access to this endpoint. * * @param {string} teamId * @param {string[]} queries * @param {string} search * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async listMemberships(teamId: string, queries?: string[], search?: string): Promise { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } - const apiPath = '/teams/{teamId}/memberships'.replace('{teamId}', teamId); - const payload: Payload = {}; - + const params: Params = {}; if (typeof queries !== 'undefined') { - payload['queries'] = queries; + params['queries'] = queries; } - if (typeof search !== 'undefined') { - payload['search'] = search; + params['search'] = search; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Create team membership * - * 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. - * + * Invite a new member to join your team. Provide an ID for existing users, or invite unregistered users using an email or phone number. If initiated from a Client SDK, Appwrite will send an email or sms with a link to join the team to the invited user, and an account will be created for them if one doesn't exist. If initiated from a Server SDK, the new member will be added automatically to the team. + +You only need to provide one of a user ID, email, or phone number. Appwrite will prioritize accepting the user ID > email > phone number if you provide more than one of these parameters. + +Use the `url` parameter to redirect the user from the invitation email to your app. After the user is redirected, use the [Update Team Membership Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus) endpoint to allow the user to accept the invitation to the team. + +Please note that to avoid a [Redirect Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) Appwrite will accept the only redirect URLs under the domains you have added as a platform on the Appwrite Console. + * * @param {string} teamId * @param {string[]} roles @@ -228,257 +230,262 @@ export class Teams extends Service { * @param {string} url * @param {string} name * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async createMembership(teamId: string, roles: string[], email?: string, userId?: string, phone?: string, url?: string, name?: string): Promise { 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 = {}; - + const params: Params = {}; if (typeof email !== 'undefined') { - payload['email'] = email; + params['email'] = email; } - if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof phone !== 'undefined') { - payload['phone'] = phone; + params['phone'] = phone; } - if (typeof roles !== 'undefined') { - payload['roles'] = roles; + params['roles'] = roles; } - if (typeof url !== 'undefined') { - payload['url'] = url; + params['url'] = url; } - if (typeof name !== 'undefined') { - payload['name'] = name; + params['name'] = name; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('post', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'post', + uri, + apiHeaders, + params + ); + } /** * Get team membership * - * Get a team member by the membership unique id. All team members have read - * access for this resource. + * Get a team member by the membership unique id. All team members have read access for this resource. * * @param {string} teamId * @param {string} membershipId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async getMembership(teamId: string, membershipId: string): Promise { 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 params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Update membership * - * Modify the roles of a team member. Only team members with the owner role - * have access to this endpoint. Learn more about [roles and - * permissions](https://appwrite.io/docs/permissions). - * + * Modify the roles of a team member. Only team members with the owner role have access to this endpoint. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). + * * @param {string} teamId * @param {string} membershipId * @param {string[]} roles * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updateMembership(teamId: string, membershipId: string, roles: string[]): Promise { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } - if (typeof membershipId === 'undefined') { throw new AppwriteException('Missing required parameter: "membershipId"'); } - 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 = {}; - + const params: Params = {}; if (typeof roles !== 'undefined') { - payload['roles'] = roles; + params['roles'] = roles; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** * Delete team membership * - * This endpoint allows a user to leave a team or for a team owner to delete - * the membership of any other team member. You can also use this endpoint to - * delete a user membership even if it is not accepted. + * This endpoint allows a user to leave a team or for a team owner to delete the membership of any other team member. You can also use this endpoint to delete a user membership even if it is not accepted. * * @param {string} teamId * @param {string} membershipId * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise<{}>} + */ async deleteMembership(teamId: string, membershipId: string): Promise<{}> { 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 params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('delete', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'delete', + uri, + apiHeaders, + params + ); + } /** * Update team membership status * - * 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. - * + * 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 * @param {string} membershipId * @param {string} userId * @param {string} secret * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updateMembershipStatus(teamId: string, membershipId: string, userId: string, secret: string): Promise { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } - if (typeof membershipId === 'undefined') { throw new AppwriteException('Missing required parameter: "membershipId"'); } - if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } - 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 = {}; - + const params: Params = {}; if (typeof userId !== 'undefined') { - payload['userId'] = userId; + params['userId'] = userId; } - if (typeof secret !== 'undefined') { - payload['secret'] = secret; + params['secret'] = secret; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('patch', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'patch', + uri, + apiHeaders, + params + ); + } /** * Get team preferences * - * 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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async getPrefs(teamId: string): Promise { if (typeof teamId === 'undefined') { throw new AppwriteException('Missing required parameter: "teamId"'); } - const apiPath = '/teams/{teamId}/prefs'.replace('{teamId}', teamId); - const payload: Payload = {}; - + const params: Params = {}; const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('get', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); - } + } + return await this.client.call( + 'get', + uri, + apiHeaders, + params + ); + } /** * Update preferences * - * 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 * @throws {AppwriteException} - * @returns {Promise} - */ + * @returns {Promise} + */ async updatePrefs(teamId: string, prefs: object): Promise { 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 = {}; - + const params: Params = {}; if (typeof prefs !== 'undefined') { - payload['prefs'] = prefs; + params['prefs'] = prefs; } - const uri = new URL(this.client.config.endpoint + apiPath); - return await this.client.call('put', uri, { + + const apiHeaders: { [header: string]: string } = { 'content-type': 'application/json', - }, payload); + } + + return await this.client.call( + 'put', + uri, + apiHeaders, + params + ); } -}; +}