### Basic API Call Example (GET) Source: https://docs.cloudbase.net/api-reference/webv2/apis This example shows how to retrieve a list of products by calling the `methodLabel` method of the `apisLabel` API connector using the GET method, specifying a category. ```APIDOC ## GET /methodLabel ### Description Retrieves a list of products by calling the `methodLabel` method of the `apisLabel` API connector using GET. ### Method GET ### Endpoint `apis["apisLabel"].get({ path: "methodLabel", body: { category } }) ### Parameters #### Request Body - **category** (string) - Required - The category of products to retrieve. ### Request Example ```javascript apis["apisLabel"].get({ path: "methodLabel", body: { category: "electronics" } }); ``` ### Response #### Success Response (200) - **result** (any) - The list of products. ``` -------------------------------- ### Initialize CloudBase and Database Source: https://docs.cloudbase.net/api-reference/webv2/database/command Initialize the CloudBase SDK and get a database instance. This setup is required before using any database operations. ```javascript import cloudbase from "@cloudbase/js-sdk"; const app = cloudbase.init({ env: "your-env-id", }); const db = app.database(); const _ = db.command; ``` -------------------------------- ### Install Node.js Adapter Source: https://docs.cloudbase.net/api-reference/webv2/adapter/node-adapter Install the Node.js adapter using npm. This is the first step to using Cloudbase services in a Node.js environment. ```bash npm i @cloudbase/adapter-node ``` -------------------------------- ### Install Adapter Interface Module Source: https://docs.cloudbase.net/api-reference/webv2/adapter Install the official interface declaration module for adapter development using npm or yarn. ```bash npm i @cloudbase/adapter-interface ``` ```bash yarn add @cloudbase/adapter-interface ``` -------------------------------- ### Multi-Method API Calls Example Source: https://docs.cloudbase.net/api-reference/webv2/apis Illustrates making sequential API calls using different HTTP methods (POST, GET, DELETE) to the same 'methodLabel' path. ```javascript // Using different HTTP methods async function multiMethodExample() { // POST request const createResult = await apis["apisLabel"].post({ path: "methodLabel", body: { name: "New Item" }, }); // GET request const getResult = await apis["apisLabel"].get({ path: "methodLabel", }); // DELETE request const deleteResult = await apis["apisLabel"].delete({ path: "methodLabel", }); } ``` -------------------------------- ### Install UniApp Adapter Source: https://docs.cloudbase.net/api-reference/webv2/adapter/uniapp-adapter Install the UniApp Adapter using npm. This is the first step to integrate Cloudbase into your UniApp project. ```bash npm install @cloudbase/adapter-uni-app ``` -------------------------------- ### Install Cocos Native Adapter Source: https://docs.cloudbase.net/api-reference/webv2/adapter/cocos-adapter Install the Cloudbase JS SDK and the Cocos Native adapter using npm. ```bash npm install @cloudbase/js-sdk @cloudbase/adapter-cocos_native ``` -------------------------------- ### Password Reset Examples Source: https://docs.cloudbase.net/api-reference/webv2/authentication Examples demonstrating how to reset a user's password using the `resetPasswordForOld` method, including handling different error codes and validating password strength. ```APIDOC ## Basic Password Reset ### Description Resets the user's password using their old password. ### Method `auth.resetPasswordForOld({ new_password: string, old_password: string })` ### Request Example ```javascript const { data, error } = await auth.resetPasswordForOld({ new_password: "newSecurePassword123", old_password: "oldPassword123", }); if (error) { console.error("密码重置失败:", error.message); } else { console.log("密码重置成功"); console.log("用户信息:", data.user); console.log("会话信息:", data.session); } ``` ## Change Password with Error Handling ### Description Provides a function to change the password with specific error handling for common issues like invalid old password or weak new password. ### Method `changePassword(oldPassword: string, newPassword: string): Promise` ### Request Example ```javascript async function changePassword(oldPassword, newPassword) { const { data, error } = await auth.resetPasswordForOld({ new_password: newPassword, old_password: oldPassword, }); if (error) { switch (error.code) { case "invalid_password": alert("旧密码不正确"); break; case "password_too_weak": alert("新密码强度不够,请使用更复杂的密码"); break; default: alert("密码重置失败: " + error.message); } return false; } else { alert("密码重置成功"); return true; } } // Example form submission handling document .getElementById("passwordForm") .addEventListener("submit", async (e) => { e.preventDefault(); const oldPassword = document.getElementById("oldPassword").value; const newPassword = document.getElementById("newPassword").value; const confirmPassword = document.getElementById("confirmPassword").value; if (newPassword !== confirmPassword) { alert("新密码和确认密码不一致"); return; } const success = await changePassword(oldPassword, newPassword); if (success) { window.location.href = "/dashboard"; } }); ``` ## Password Strength Validation ### Description Validates if a given password meets the required strength criteria (minimum length, uppercase, lowercase, numbers, special characters). ### Method `validatePassword(password: string): boolean` ### Request Example ```javascript function validatePassword(password) { const minLength = 8; const hasUpperCase = /[A-Z]/.test(password); const hasLowerCase = /[a-z]/.test(password); const hasNumbers = /\d/.test(password); const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password); return ( password.length >= minLength && hasUpperCase && hasLowerCase && hasNumbers && hasSpecialChar ); } async function resetPasswordWithValidation(oldPassword, newPassword) { if (!validatePassword(newPassword)) { alert("密码必须包含大小写字母、数字和特殊字符,且长度不少于8位"); return false; } const { data, error } = await auth.resetPasswordForOld({ new_password: newPassword, old_password: oldPassword, }); if (error) { alert("密码重置失败: " + error.message); return false; } alert("密码重置成功"); return true; } ``` ## Comprehensive Error Handling for Password Reset ### Description Demonstrates comprehensive error handling for the password reset process, covering various error codes and providing user-friendly feedback. ### Method `auth.resetPasswordForOld({ new_password: string, old_password: string })` ### Request Example ```javascript try { const { data, error } = await auth.resetPasswordForOld({ new_password: "newPassword123", old_password: "wrongOldPassword", }); if (error) { switch (error.code) { case "invalid_password": console.error("旧密码不正确,请重新输入"); document.getElementById("oldPassword").classList.add("error"); break; case "password_too_weak": console.error("新密码强度不足,请使用更复杂的密码"); document.getElementById("newPassword").classList.add("error"); break; case "user_not_found": console.error("用户不存在,请重新登录"); window.location.href = "/login"; break; case "token_expired": console.error("会话已过期,请重新登录"); window.location.href = "/login"; break; case "permission_denied": console.error("权限不足,无法修改密码"); break; case "unreachable": console.error("网络连接失败,请检查网络设置后重试"); break; case "resource_exhausted": console.error("重置频率过高,请稍后重试"); break; default: console.error("密码重置失败:", error.message); } } else { console.log("密码重置成功"); } } catch (error) { console.error("网络错误:", error); } ``` ``` -------------------------------- ### Multi-Method API Call Examples Source: https://docs.cloudbase.net/api-reference/webv2/apis Illustrates how to use different HTTP methods (POST, GET, DELETE) for various operations on the same API connector and endpoint. ```APIDOC ## Multiple HTTP Method Examples ### Description Demonstrates the usage of different HTTP methods (POST, GET, DELETE) for interacting with API endpoints. ### POST Request Example ```javascript // Create a new item await apis["apisLabel"].post({ path: "methodLabel", body: { name: "New Item" } }); ``` ### GET Request Example ```javascript // Retrieve an item await apis["apisLabel"].get({ path: "methodLabel" }); ``` ### DELETE Request Example ```javascript // Delete an item await apis["apisLabel"].delete({ path: "methodLabel" }); ``` ``` -------------------------------- ### Basic API Call Example (POST) Source: https://docs.cloudbase.net/api-reference/webv2/apis This example demonstrates how to call a specific method (`methodLabel`) of an API connector (`apisLabel`) using the POST method, passing a `userId` in the request body. ```APIDOC ## POST /methodLabel ### Description Calls the `methodLabel` method of the `apisLabel` API connector using POST. ### Method POST ### Endpoint `apis["apisLabel"].post({ path: "methodLabel", body: { userId } }) ### Parameters #### Request Body - **userId** (string) - Required - The ID of the user. ### Request Example ```javascript apis["apisLabel"].post({ path: "methodLabel", body: { userId: "someUserId" } }); ``` ### Response #### Success Response (200) - **result** (any) - The data returned from the API call. ``` -------------------------------- ### Initialize SDK with English Language Source: https://docs.cloudbase.net/api-reference/webv2/initialization Example of initializing the Cloudbase SDK to use English for prompts and messages. ```APIDOC ## Initialize SDK with English Language ### Description Initializes the Cloudbase SDK, setting the language to English for user-facing messages and prompts. ### Method `cloudbase.init(config)` ### Parameters #### Request Body - **env** (string) - Required - Your Cloudbase environment ID. - **lang** (string) - Optional - Set to `en-US` to use English. Defaults to `zh-CN`. ### Request Example ```javascript import cloudbase from "@cloudbase/js-sdk"; const app = cloudbase.init({ env: "your-env-id", // Replace with your environment ID lang: "en-US", }); ``` ``` -------------------------------- ### Registration Form Implementation Source: https://docs.cloudbase.net/api-reference/webv2/authentication This example shows how to implement a registration form in a web application, handling the initiation of the registration process and the completion of verification. ```APIDOC ## Registration Form Implementation ### Description This section provides a client-side implementation for a registration form. It details how to initiate the registration process upon form submission and how to handle the subsequent verification step, including user feedback and redirection. ### Functions - **`startRegistration(email, password, nickname)`**: Initiates the registration process by sending user credentials to the server. It handles the API call and updates the UI to prompt for verification code. - **`completeRegistration(verificationCode)`**: Completes the registration by submitting the verification code. It handles the API response, provides user feedback (success or error messages), and redirects the user upon successful completion. ### Event Listeners - **Registration Form Submit**: Listens for the submit event on the registration form. It prevents the default form submission, retrieves email and password, and calls `startRegistration`. - **Verification Form Submit**: Listens for the submit event on the verification code form. It prevents the default submission, retrieves the verification code, and calls `completeRegistration`. ### Code Example ```javascript let signUpVerify = null; async function startRegistration(email, password) { const { data, error } = await auth.signUp({ email: email, password: password, }); if (error) { console.error("Failed to send verification code:", error.message); document.getElementById("error").innerText = "Failed to send verification code: " + error.message; return false; } else { console.log("Verification code sent"); signUpVerify = data.verifyOtp; // Show verification code input field document.getElementById("verificationSection").style.display = "block"; document.getElementById("registrationSection").style.display = "none"; // Update hint message explaining the intelligent judgment logic document.getElementById("verificationHint").innerText = "Please enter the verification code, and the system will automatically determine if you are registering a new account or logging into an existing one"; return true; } } async function completeRegistration(verificationCode) { if (!signUpVerify) { console.error("Registration process not started"); return false; } const { data, error } = await signUpVerify({ token: verificationCode }); if (error) { console.error("Verification failed:", error.message); document.getElementById("error").innerText = "Verification failed: " + error.message; return false; } else { // Intelligent judgment result feedback if (data.user?.email) { console.log("Intelligent registration and login successful"); document.getElementById("success").innerText = data.user?.created_at ? "New user registered successfully, welcome aboard!" : "Login successful, welcome back!"; } // Automatic redirection to the dashboard setTimeout(() => { window.location.href = "/dashboard"; }, 2000); return true; } } // Registration form submission document .getElementById("registerForm") .addEventListener("submit", async (e) => { e.preventDefault(); const email = document.getElementById("email").value; const password = document.getElementById("password").value; const nickname = document.getElementById("nickname").value; await startRegistration(email, password, nickname); }); // Verification code form submission document .getElementById("verificationForm") .addEventListener("submit", async (e) => { e.preventDefault(); const code = document.getElementById("verificationCode").value; await completeRegistration(code); }); ``` ``` -------------------------------- ### Batch Update Example Source: https://docs.cloudbase.net/api-reference/webv2/postgresql/update Example of batch updating records in the 'articles' table. ```APIDOC // Update all articles with status 'draft' to 'published' const { error } = await db .from("articles") .update({ status: "published" }) .eq("status", "draft"); console.log('Batch update result:', error ? 'Failed' : 'Success'); ``` -------------------------------- ### Install Cloudbase JS SDK via npm/yarn Source: https://docs.cloudbase.net/api-reference/webv2/initialization Install the SDK using your preferred package manager. This command adds the SDK to your project dependencies. ```bash # npm npm install @cloudbase/js-sdk -S # yarn yarn add @cloudbase/js-sdk ``` -------------------------------- ### Custom API Call Example (PUT) Source: https://docs.cloudbase.net/api-reference/webv2/apis This example demonstrates how to make a custom API call using the `request` method, specifying the HTTP method as PUT, along with custom headers and a request body. ```APIDOC ## PUT /methodLabel (Custom Request) ### Description Performs a custom PUT request to the `methodLabel` endpoint using the `request` method, including custom headers and body. ### Method PUT ### Endpoint `apis["apisLabel"].request({ method: "PUT", path: "methodLabel", headers: {...}, body: {...} }) ### Parameters #### Request Body - **data** (string) - Required - Custom data payload. #### Headers - **X-Custom-Header** (string) - Required - A custom header value. ### Request Example ```javascript apis["apisLabel"].request({ method: "PUT", path: "methodLabel", headers: { "X-Custom-Header": "value" }, body: { data: "custom data" } }); ``` ### Response #### Success Response (200) - **result** (any) - The response data from the API. ``` -------------------------------- ### Initialize SDK for Singapore Region Source: https://docs.cloudbase.net/api-reference/webv2/initialization Example of initializing the Cloudbase SDK specifically for the Singapore region. ```APIDOC ## Initialize SDK for Singapore Region ### Description Initializes the Cloudbase SDK, specifying the Singapore region for service requests. ### Method `cloudbase.init(config)` ### Parameters #### Request Body - **env** (string) - Required - Your Cloudbase environment ID. - **region** (string) - Required - Set to `ap-singapore` for the Singapore region. ### Request Example ```javascript import cloudbase from "@cloudbase/js-sdk"; const app = cloudbase.init({ env: "your-env-id", // Replace with your environment ID region: "ap-singapore", }); ``` ``` -------------------------------- ### Initialize CloudBase Application and Get APIs Instance Source: https://docs.cloudbase.net/api-reference/webv2/apis Initializes the CloudBase application with environment details and retrieves the APIs instance for making connector calls. ```javascript import cloudbase from "@cloudbase/js-sdk"; // Initialize CloudBase application const app = cloudbase.init({ env: "your-env-id", // Replace with your environment ID region: "ap-shanghai", // Region, defaults to Shanghai accessKey: "", // Enter the generated Publishable Key, }); // Get apis instance const apis = app.apis; ``` -------------------------------- ### Basic Text Generation Example Source: https://docs.cloudbase.net/api-reference/webv2/ai Demonstrates a simple call to generate text using the ChatModel. Ensure the model name and messages are correctly formatted. ```typescript const model = ai.createModel("hunyuan-exp"); const result = await model.generateText({ model: "hunyuan-lite", messages: [{ role: "user", content: "你好,请你介绍一下李白" }], }); console.log("生成的文本:", result.text); console.log("消耗的token:", result.usage); ``` -------------------------------- ### Initialize Cloudbase SDK with Adapter Configuration Source: https://docs.cloudbase.net/api-reference/webv2/adapter Demonstrates initializing the Cloudbase SDK with custom adapter configurations. It shows how to create an event bus instance, inject it into the adapter, and then initialize the Cloudbase app with environment and authentication details. ```javascript // 创建事件总线实例 const EVENT_BUS = new EventBus(); // 配置并使用适配器,将 EVENT_BUS 注入给 genAdapter cloudbase.useAdapters(adapter, { EVENT_BUS }); const app = cloudbase.init({ env: '环境ID', appSign: '应用标识', appSecret: { appAccessKeyId: '应用凭证版本号' appAccessKey: '应用凭证' } }); const auth = app.auth(); ``` -------------------------------- ### Call Read-Only Function with GET Request Source: https://docs.cloudbase.net/api-reference/webv2/postgresql/rpc Utilize HTTP GET requests for read-only functions (IMMUTABLE or STABLE) to improve caching. This example calls the 'add_numbers' function using GET. ```javascript // 使用 GET 请求调用只读函数 const { data, error } = await db.rpc( "add_numbers", { a: 1, b: 2 }, { get: true } ); ``` -------------------------------- ### Development Environment Startup Commands Source: https://docs.cloudbase.net/api-reference/webv2/adapter/uniapp-adapter Commands to start development servers for different platforms including H5, WeChat Mini Program, Douyin Mini Program, and Alipay Mini Program. For App development, use HBuilderX. ```bash # H5 开发 npm run dev:h5 # 微信小程序开发 npm run dev:mp-weixin # 抖音小程序开发 npm run dev:mp-toutiao # 支付宝小程序开发 npm run dev:mp-alipay # App (iOS/Android) 开发 # 1. 使用 HBuilderX 打开项目 # 2. 在顶部菜单栏选择【运行】->【运行到手机或模拟器】-> 选择您的设备 ``` -------------------------------- ### Call APIs Connector Method (GET) Source: https://docs.cloudbase.net/api-reference/webv2/apis Example of calling a specific method ('methodLabel') on an APIs connector ('apisLabel') using the GET method. Includes basic error handling. ```javascript // Call the methodLabel method of the APIs connector named "apisLabel", using GET call async function getProductList(category: string) { try { const result = await apis["apisLabel"].get({ path: "methodLabel", body: { category }, }); return result; } catch (error) { console.error("Call failed:", error); throw error; } } ``` -------------------------------- ### Initialization Source: https://docs.cloudbase.net/api-reference/webv2/ai Initialize the Cloudbase SDK with your environment details and obtain an AI instance. ```APIDOC ## Initialization ### Description Initialize the Cloudbase SDK with your environment ID, region, and publishable key. Then, obtain an AI instance to access AI functionalities. ### Code ```javascript import cloudbase from "@cloudbase/js-sdk"; // Initialize const app = cloudbase.init({ env: "your-env-id", // Replace with your environment ID region: "ap-shanghai", // Region, defaults to Shanghai accessKey: "", // Enter your generated Publishable Key }); // If accessKey is provided, this step is not needed await app.auth.signInAnonymously(); const ai = app.ai(); ``` ``` -------------------------------- ### Initialize Cloudbase SDK and Use Storage Source: https://docs.cloudbase.net/api-reference/webv2/storage Initializes the Cloudbase SDK and demonstrates basic storage operations including upload, download, creating signed URLs, and removing files. Ensure you replace 'your-env-id' with your actual environment ID. ```javascript import cloudbase from "@cloudbase/js-sdk"; const app = cloudbase.init({ env: "your-env-id", }); // 使用 Supabase 风格的 API const storage = app.storage.from(); // 上传文件 const { data, error } = await storage.upload("images/photo.jpg", file); // 下载文件 const { data: blob } = await storage.download( "cloud://envId.xxx/images/photo.jpg" ); // 创建签名 URL const { data: { signedUrl }, } = await storage.createSignedUrl( "[images/photo.jpg](cloud://envId.xxx/images/photo.jpg)", 3600 ); // 删除文件 await storage.remove([ "[images/photo.jpg](cloud://envId.xxx/images/photo.jpg)", ]); ``` -------------------------------- ### Create PostgreSQL Functions Source: https://docs.cloudbase.net/api-reference/webv2/postgresql/rpc Examples of SQL functions that can be called via RPC. These include a simple addition function, a function to search articles, and a function to get article statistics. ```sql -- 创建一个简单的加法函数 CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ SELECT a + b; $$ LANGUAGE sql; -- 创建一个查询文章的函数 CREATE OR REPLACE FUNCTION search_articles(keyword text) RETURNS SETOF articles AS $$ SELECT * FROM articles WHERE title ILIKE '%' || keyword || '%'; $$ LANGUAGE sql; -- 创建一个统计函数 CREATE OR REPLACE FUNCTION get_article_stats() RETURNS json AS $$ SELECT json_build_object( 'total', COUNT(*), 'latest', MAX(published_at) ) FROM articles; $$ LANGUAGE sql; ``` -------------------------------- ### Using GET Request for Read-Only Functions Source: https://docs.cloudbase.net/api-reference/webv2/postgresql/rpc How to use the `get: true` option to make RPC calls using HTTP GET for read-only functions, improving cacheability. ```APIDOC ## Using GET Request for Read-Only Functions ### Description For PostgreSQL functions marked as `IMMUTABLE` or `STABLE` (i.e., read-only), you can use the `get: true` option in the `options` parameter. This instructs the SDK to use an HTTP GET request, which can benefit from browser and server-side caching. ### Method `db.rpc(functionName, params, { get: true }) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters - **functionName** (string) - Required - The name of the read-only function. - **params** (object) - Required - Parameters for the function. - **options** (object) - Required - Must include `{ get: true }`. ### Request Example ```javascript // Call a read-only function using GET const { data, error } = await db.rpc( "add_numbers", { a: 1, b: 2 }, { get: true } // Use GET request ); console.log(data); // 3 ``` ### Response #### Success Response (200) - **data** - The result of the function call. - **error** - Null if successful. #### Response Example ```json 3 ``` ``` -------------------------------- ### Initialize CloudBase and Auth, then Redirect Source: https://docs.cloudbase.net/api-reference/webv2/authentication Initializes CloudBase with environment and region, then obtains the auth instance. Finally, it calls `toDefaultLoginPage` with specified parameters to redirect the user. ```typescript const app = cloudbase.init({ env: "xxxx-yyy", region: "ap-shanghai", // 不传默认为上海地域 }); const auth = app.auth(); await auth.toDefaultLoginPage({ config_version: "env", app_id: "app-xxx", redirect_uri: "xxx", }); ``` -------------------------------- ### Update Data Example Source: https://docs.cloudbase.net/api-reference/webv2/postgresql/update Example of updating a single record in the 'articles' table. ```APIDOC // Update the record with id 1 in the articles table, changing the title field to "New Title" const { error } = await db .from("articles") .update({ title: "New Title" }) .eq("id", 1); console.log('Update result:', error ? 'Failed' : 'Success'); ``` -------------------------------- ### Meeting Transcription System Usage Example Source: https://docs.cloudbase.net/api-reference/webv2/ai Demonstrates how to instantiate the MeetingTranscriptionSystem and use its methods to generate meeting minutes from an audio file and to directly transcribe a meeting. ```typescript // 使用示例 const meetingSystem = new MeetingTranscriptionSystem("meeting-bot-id"); // 生成会议纪要 const minutes = await meetingSystem.generateMeetingMinutes( "meeting-recording.mp3", "季度规划会议", ["张三", "李四", "王五"] ); console.log(minutes); // 直接转录会议 const meetingData = await meetingSystem.transcribeMeeting("team-meeting.mp3"); console.log("会议摘要:", meetingData.summary); console.log("行动项:", meetingData.actionItems); ``` -------------------------------- ### Create AI Model Instances Source: https://docs.cloudbase.net/api-reference/webv2/ai Demonstrates creating instances of different AI models, such as 'hunyuan-exp' and 'hunyuan-lite'. Allows for managing multiple models for various scenarios. ```javascript // Create Hunyuan experience version model const model = ai.createModel("hunyuan-exp"); // Create Hunyuan lite version model const liteModel = ai.createModel("hunyuan-lite"); ``` ```javascript // Create multiple model instances for different scenarios const expModel = ai.createModel("hunyuan-exp"); // Experience version, full features const liteModel = ai.createModel("hunyuan-lite"); // Lite version, fast response const proModel = ai.createModel("hunyuan-pro"); // Professional version, stronger performance // Select different models based on needs async function generateWithModel(scenario: string, content: string) { let selectedModel; switch (scenario) { case "creative": selectedModel = expModel; break; case "quick": selectedModel = liteModel; break; case "professional": selectedModel = proModel; break; default: selectedModel = liteModel; } const result = await selectedModel.generateText({ model: scenario, messages: [{ role: "user", content: content }], }); return result.text; } ``` -------------------------------- ### Initialize Node.js Adapter Source: https://docs.cloudbase.net/api-reference/webv2/adapter/node-adapter Initialize the Cloudbase SDK with the Node.js adapter. Replace 'your-env' with your actual environment ID. ```javascript const cloudbase = require("@cloudbase/js-sdk"); const adapter = require("@cloudbase/adapter-node"); // 使用 Node.js 适配器 cloudbase.useAdapters(adapter); const app = cloudbase.init({ env: "your-env", // 需替换为实际使用环境 id }); ``` -------------------------------- ### Initialize Cloudbase and Listen for Auth State Changes Source: https://docs.cloudbase.net/api-reference/webv2/authentication_v2 Initializes the Cloudbase SDK with environment and region, then sets up a listener for authentication state changes like sign-in, sign-out, and credential errors. It also includes an example of signing out. ```javascript const app = cloudbase.init({ env: "xxxx-yyy", region: "ap-shanghai", // 不传默认为上海地域 }); const auth = app.auth(); // 监听登录态变化 auth.onLoginStateChanged((params) => { console.log(params); const { eventType } = params?.data || {}; switch (eventType) { case "sign_in": // 登录成功 break; case "sign_out": // 退出登录成功 break; case "credentials_error": // 权限失效 break; default: return; } }); await auth.signOut(); ``` -------------------------------- ### Error Response Example Source: https://docs.cloudbase.net/api-reference/webv2/authentication_v2 This is an example of an error response when a user's request frequency is too high or other risks are detected. The client should display the `error_description` to the user. ```APIDOC ## Error Response ### Description This response is returned when the user's request frequency is too high or other risks are detected. ### Response Body ```json { "error": "resource_exhausted", "error_description": "Your operation is too frequent, please try again later" } ``` ### Handling Display the `error_description` to the user, potentially with multi-language support. ``` -------------------------------- ### POST /auth/v1/captcha/init Source: https://docs.cloudbase.net/api-reference/webv2/authentication_v2 Initialize captcha. ```APIDOC ## POST /auth/v1/captcha/init ### Description 初始化验证码 ### Method POST ### Endpoint https://${env}.ap-shanghai.tcb-api.tencentcloudapi.com/auth/v1/captcha/init ### Parameters #### Request Body - **redirect_uri** (string) - Required - 验证码验证完成后的地址。 - **state** (string) - Required - 系统状态字符串,该字符串在验证码验证完成后后将 state 携带到。 ### Request Example ```json { "redirect_uri": "https://example.com/callback", "state": "your_state string" } ``` ### Response #### Success Response (200) - **url** (string) - 如果用户请求比较频繁或存在其他风险,验证码服务会返回此字段,客户端需要通过浏览器或 webview/iframe 等打开此 URL 进行验证。 - **expires_in** (number) - URL 的过期时间,单位为秒。 #### Response Example ```json { "url": "https://exmaple.com/captcha.html", "expires_in": 600 } ``` ``` -------------------------------- ### Recommended File Path Structure Source: https://docs.cloudbase.net/api-reference/webv2/storage Demonstrates the recommended way to structure file paths using forward slashes for directory separation and avoiding leading slashes. ```plaintext // ✅ 推荐 "images/avatars/user-123.jpg"; "documents/reports/2024/report.pdf"; "uploads/temp/file-abc.txt"; // ❌ 不推荐 "/images/photo.jpg"; // 不要以 / 开头 "photo.jpg"; // 缺少目录结构 ``` -------------------------------- ### Start Countdown for Resend Source: https://docs.cloudbase.net/api-reference/webv2/authentication This utility function starts a countdown timer, typically used after sending a verification code to disable the resend button for a specified duration. ```APIDOC ## Start Countdown for Resend ### Description Initiates a countdown timer that disables a 'Resend' button and updates its text to show the remaining time. Once the countdown finishes, the button is re-enabled. ### Function Signature `startCountdown(seconds)` ### Parameters - **seconds** (number) - Required - The duration of the countdown in seconds. ``` -------------------------------- ### Initialize Cloudbase and Link Google Account Source: https://docs.cloudbase.net/api-reference/webv2/authentication Initializes the Cloudbase SDK and demonstrates how to initiate the process of linking a Google account. It includes an event listener for authentication state changes, specifically for the `BIND_IDENTITY` event, to handle success or failure. ```javascript const app = cloudbase.init({ env: "your-env-id", // 替换为您的环境ID region: "ap-shanghai", // 地域,默认为上海 accessKey: "", // 填入生成的 Publishable Key, auth: { detectSessionInUrl: true, // 可选:自动检测 URL 中的 OAuth 参数 }, }); // 监听身份源绑定事件 auth.onAuthStateChange((event, session, info) => { console.log("认证状态变化:", { event, session, info }); switch (event) { case "BIND_IDENTITY": if (!!info.error) { console.error("身份源绑定失败:", info.error); // 可以在这里添加UI错误提示 } else { console.log("身份源已绑定"); // 重新加载身份源列表 await auth.getUserIdentities(); } break; default: return; } }); try { const { data, error } = await auth.linkIdentity({ provider: "google", }); if (error) { console.error("绑定身份源失败:", error.message); // 处理绑定失败逻辑 return; } console.log("身份源绑定请求已发送,等待用户授权..."); // 绑定请求成功,等待用户完成OAuth授权流程 } catch (error) { console.error("调用linkIdentity方法时发生错误:", error); // 处理网络错误或其他异常 } ``` -------------------------------- ### Platform Matching Function (Cocos Example) Source: https://docs.cloudbase.net/api-reference/webv2/adapter Implement the `isMatch` function to determine if the current environment matches the adapter's target platform. This example checks for Cocos native platform specific variables and APIs. ```javascript function isMatch(): boolean { if (typeof cc === "undefined") { return false; } if (typeof WebSocket === "undefined") { return false; } if (typeof XMLHttpRequest === "undefined") { return false; } if (!cc.game) { return false; } if (typeof cc.game.on !== "function") { return false; } if (!cc.game.EVENT_HIDE) { return false; } if (!cc.game.EVENT_SHOW) { return false; } if (!cc.sys) { return false; } if (!cc.sys.isNative) { return false; } return true; } ``` -------------------------------- ### Conditional Delete Source: https://docs.cloudbase.net/api-reference/webv2/postgresql/delete Example of deleting all articles with the status 'draft'. ```APIDOC // Delete all articles with status 'draft' const { error } = await db.from("articles").delete().eq("status", "draft"); console.log('Conditional deletion result:', error ? 'Failed' : 'Success'); ``` -------------------------------- ### Batch Feedback Processing Example Source: https://docs.cloudbase.net/api-reference/webv2/ai Demonstrates how to use the BatchFeedbackProcessor class to add and process feedback items in batches. Includes error handling for failed batch operations. ```javascript class BatchFeedbackProcessor { constructor(botId) { this.botId = botId; this.feedbackQueue = []; } addFeedback(recordId, type, score, text, tags) { this.feedbackQueue.push({ recordId, type, score, text, tags, timestamp: new Date().toISOString(), // input: "", // 需要根据实际情况获取 // type: feedback.type, }); } async processBatch() { if (this.feedbackQueue.length === 0) { console.log("反馈队列为空"); return; } const batch = this.feedbackQueue.splice(0, 10); // 一次处理10个 const promises = batch.map(feedback => { // 模拟发送反馈到API return new Promise(resolve => setTimeout(() => { console.log("发送反馈:", feedback); resolve(); }, 100)); }); try { await Promise.all(promises); console.log(`成功处理 ${batch.length} 个反馈`); } catch (error) { console.error("批量处理反馈失败:", error); // 将失败的反馈重新加入队列 this.feedbackQueue.unshift(...batch); } } getQueueSize() { return this.feedbackQueue.length; } } // 使用示例 const feedbackProcessor = new BatchFeedbackProcessor("botId-xxx"); // 添加多个反馈 feedbackProcessor.addFeedback("record-1", "upvote", 5, "回答很棒", [ "准确", "详细", ]); feedbackProcessor.addFeedback("record-2", "downvote", 2, "回答不够准确", [ "不准确", ]); console.log("当前队列大小:", feedbackProcessor.getQueueSize()); ``` -------------------------------- ### Initialization Source: https://docs.cloudbase.net/api-reference/webv2/authentication Initialize the Cloudbase SDK with your environment ID and other configuration options. ```APIDOC ## Initialization ### Description Initialize the Cloudbase SDK with your environment ID and other configuration options. The `accessKey` is your Publishable Key, and `detectSessionInUrl` is an optional parameter to automatically detect OAuth parameters from the URL. ### Code ```javascript import cloudbase from "@cloudbase/js-sdk"; // Initialize const app = cloudbase.init({ env: "your-env-id", // Replace with your environment ID region: "ap-shanghai", // Region, defaults to Shanghai accessKey: "", // Enter your generated Publishable Key auth: { detectSessionInUrl: true, // Optional: Automatically detect OAuth parameters in the URL, suitable for signInWithOAuth, linkIdentity }, }); const auth = app.auth; ``` ``` -------------------------------- ### Get Conversation Details Source: https://docs.cloudbase.net/api-reference/webv2/ai Retrieves the details and message history of a specific conversation. ```APIDOC ## Get Conversation Details ### Description Fetches the details and historical messages of a given conversation. ### Method `ai.bot.getConversation(params)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **botId** (string) - Required - The ID of the bot. - **conversationId** (string) - Required - The ID of the conversation to retrieve. ### Request Example ```javascript const conversation = await ai.bot.getConversation({ botId: "botId-xxx", conversationId: "conv-xxx", }); ``` ### Response #### Success Response (200) - **history** (Array) - An array of message objects representing the conversation history. Each object typically contains sender and content. #### Response Example ```json { "conversationId": "conv-xxx", "title": "技术咨询对话", "history": [ { "role": "user", "content": "你好" }, { "role": "assistant", "content": "你好!有什么可以帮您的吗?" } ] } ``` ``` -------------------------------- ### Calling RPC without Parameters Source: https://docs.cloudbase.net/api-reference/webv2/postgresql/rpc Example of calling a PostgreSQL function that does not require any arguments. ```APIDOC ## Calling RPC without Parameters ### Description Shows how to call a PostgreSQL function that takes no arguments. ### Method `db.rpc(functionName)` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters - **functionName** (string) - Required - The name of the database function to call (e.g., `"get_article_stats"`). ### Request Example ```javascript // Call a statistics function const { data, error } = await db.rpc("get_article_stats"); console.log(data); // Expected output: { total: 15, latest: "2026-04-01T00:00:00Z" } ``` ### Response #### Success Response (200) - **data** - The JSON object returned by the function. - **error** - Null if successful. #### Response Example ```json { "total": 15, "latest": "2026-04-01T00:00:00Z" } ``` ``` -------------------------------- ### Get Conversation List Source: https://docs.cloudbase.net/api-reference/webv2/ai Fetches a list of conversations for a given bot, with options for pagination and filtering. ```APIDOC ## Get Conversation List ### Description Fetches a paginated list of conversations for a specified bot. ### Method `ai.bot.getConversation` ### Parameters - **botId** (string) - Required - The ID of the bot. - **pageSize** (number) - Optional - The number of conversations to return per page. - **pageNumber** (number) - Optional - The page number to retrieve. - **isDefault** (boolean) - Optional - Whether to fetch default conversations. ### Request Example ```javascript const result = await ai.bot.getConversation({ botId: "botId-xxx", pageSize: 10, pageNumber: 1, isDefault: false, }); ``` ### Response #### Success Response (200) - **total** (number) - The total number of conversations. - **conversations** (Array) - An array of conversation objects. - **title** (string) - The title of the conversation. - **messageCount** (number) - The number of messages in the conversation. #### Response Example ```json { "total": 50, "conversations": [ { "title": "Conversation Title 1", "messageCount": 15, "conversationId": "conv-id-1", "createTime": "2023-01-01T10:00:00Z", "updateTime": "2023-01-01T12:00:00Z" } ] } ``` ``` -------------------------------- ### OAuth Login Best Practices Source: https://docs.cloudbase.net/api-reference/webv2/authentication Demonstrates a complete UI interaction flow for OAuth login, including setting up authentication state change listeners and managing the OAuth process. ```APIDOC ## OAuth Login Best Practices ### Description This example illustrates a comprehensive UI interaction flow for OAuth login. It covers initializing the SDK, setting up listeners for authentication state changes, and managing the OAuth initiation process, emphasizing a smooth user experience. ### Initialization ```javascript const app = cloudbase.init({ env: "your-env-id", // Replace with your environment ID region: "ap-shanghai", // Region, defaults to Shanghai accessKey: "", // Enter your generated Publishable Key auth: { detectSessionInUrl: true, // Optional: Automatically detect OAuth parameters in the URL }, }); const auth = app.auth; ``` ### Authentication State Change Listener ```javascript async function setupAuthStateChangeListener() { try { if (!app.auth) return; // Subscribe to authentication state change events const { data } = await app.auth.onAuthStateChange( (event, session, info) => { console.log("Authentication state changed:", { event, session, info }); switch (event) { case "SIGNED_IN": if (session && session.user) { console.log("Login successful!"); } break; default: console.log("Unknown authentication event:", event); } } ); console.log("Authentication state change listener set up."); } catch (error) { console.error("Failed to set up authentication state change listener:", error); } } ``` ### OAuth Manager Class ```javascript class OAuthManager { constructor() { this.initEventListeners(); this.provider = "oauth"; // Default provider, can be changed } // Initialize event listeners initEventListeners() { // OAuth login button click event document.getElementById("oauth-login-btn").addEventListener("click", () => { this.startOAuth(); }); // Check for OAuth callback when the page loads document.addEventListener("DOMContentLoaded", () => { this.checkOAuthCallback(); }); } // Start the OAuth authorization flow async startOAuth() { try { this.showLoading(true); this.hideError(); const { data, error } = await auth.signInWithOAuth({ provider: this.provider, }); if (error) { this.handleOAuthError(error); } else { console.log("OAuth authorization link generated successfully, redirecting..."); // Best practice: Use the current window for redirection to maintain user experience window.location.href = data.url; } } catch (error) { this.handleOAuthError(error); } finally { this.showLoading(false); } } // Check for OAuth authorization callback async checkOAuthCallback() { const urlParams = new URLSearchParams(window.location.search); const code = urlParams.get("code"); // Further logic to handle the callback would go here if not using detectSessionInUrl } showLoading(show) { document.getElementById("loading").style.display = show ? "block" : "none"; } hideError() { // Implementation to hide error messages } handleOAuthError(error) { console.error("OAuth error:", error.message); // Display error message to the user } } // Initialize the authentication state change listener setupAuthStateChangeListener(); // Initialize the OAuth login manager const oAuthManager = new OAuthManager(); ``` ```