### Complete SDK Initialization Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/sdk-config.md Demonstrates a full SDK initialization with OAuth token, configuration, and logger setup. ```typescript import { InitializeBuilder, OAuthBuilder, SDKConfigBuilder, LogBuilder, Levels, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); const config = new SDKConfigBuilder() .timeout(30000) .maxRetries(5) .retryDelay(3) .autoRefreshFields(true) .pickListValidation(true) .build(); const logger = new LogBuilder() .level(Levels.DEBUG) .filePath("./sdk.log") .build(); await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .SDKConfig(config) .logger(logger) .initialize(); ``` -------------------------------- ### SDK Initialization Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/README.md Demonstrates the one-time setup required to configure the SDK with credentials and options. This includes setting the environment and token, and then initializing the SDK. ```APIDOC ## SDK Initialization ### Description Initializes the Zoho Desk Node.js SDK with necessary credentials and optional configurations. ### Method `InitializeBuilder.initialize()` ### Parameters - **environment**: Required - The Zoho Desk data center environment (e.g., US, EU, IN). - **token**: Required - The authentication token for API access. - **store**: Optional - A `TokenStore` implementation for persisting tokens. - **config**: Optional - `SDKConfigBuilder` for fine-tuning SDK behavior. - **logger**: Optional - A Winston-based logger instance. - **proxy**: Optional - `ProxyBuilder` for configuring HTTP proxy settings. ### Request Example ```typescript import { InitializeBuilder } from '@banana.inc/zoho-desk-nodejs-sdk'; import { USDataCenter } from '@banana.inc/zoho-desk-nodejs-sdk/dist/src/api/data-centers'; const token = { accessToken: 'YOUR_ACCESS_TOKEN' }; // Replace with actual token await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .initialize(); ``` ### Response - **Initializer**: A singleton instance of the Initializer, providing access to the SDK's functionality. ``` -------------------------------- ### Complete SDK Initialization with Proxy Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/proxy.md An example showing all options for SDK initialization, including authentication token, proxy configuration, logging, and SDK configurations. This demonstrates a full setup for production environments. ```typescript import { InitializeBuilder, OAuthBuilder, ProxyBuilder, LogBuilder, Levels, SDKConfigBuilder, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); const proxy = new ProxyBuilder() .host("proxy.company.com") .port(8080) .user("employee-id") .password("company-password") .build(); const logger = new LogBuilder() .level(Levels.INFO) .filePath("./sdk.log") .build(); const config = new SDKConfigBuilder() .timeout(30000) .maxRetries(3) .build(); await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .requestProxy(proxy) .logger(logger) .SDKConfig(config) .initialize(); // All API calls now route through the proxy import { createDeskClient } from "@banana.inc/zoho-desk-nodejs-sdk"; const client = createDeskClient(); const tickets = await client.tickets.get(); ``` -------------------------------- ### SDK Initialization and Client Creation Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/client-factory.md A comprehensive example demonstrating the complete lifecycle of the Zoho Desk Node.js SDK, from token building and SDK configuration to initialization, client creation, and API module usage. It also includes robust error handling for both API and SDK-specific exceptions. ```APIDOC ## SDK Initialization and Client Creation Example This example illustrates the full process of setting up and using the Zoho Desk Node.js SDK. ### Description This code snippet shows how to: 1. Build authentication tokens using `OAuthBuilder`. 2. Configure SDK settings like logging and timeouts using `LogBuilder` and `SDKConfigBuilder`. 3. Initialize the SDK with environment, token, logger, and config. 4. Create a client instance using `createDeskClient()`. 5. Access and use various API modules (e.g., `tickets`, `contacts`, `organization`). 6. Implement comprehensive error handling for `ZohoApiError` and `SDKException`. ### Method Asynchronous function execution. ### Endpoint N/A (Client-side SDK usage) ### Parameters N/A (Parameters are handled within builder methods) ### Request Example ```typescript import { InitializeBuilder, OAuthBuilder, createDeskClient, LogBuilder, Levels, SDKConfigBuilder, USDataCenter, ZohoApiError, SDKException, } from "@banana.inc/zoho-desk-nodejs-sdk"; async function main() { try { // Step 1: Build token const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); // Step 2: Configure SDK const logger = new LogBuilder() .level(Levels.INFO) .filePath("./sdk.log") .build(); const config = new SDKConfigBuilder() .timeout(30000) .maxRetries(3) .build(); // Step 3: Initialize await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .logger(logger) .SDKConfig(config) .initialize(); // Step 4: Create client const client = createDeskClient(); // Step 5: Use API modules console.log("Fetching tickets..."); const tickets = await client.tickets.get(); console.log(`Retrieved ${tickets?.length || 0} tickets`); console.log("Fetching contacts..."); const contacts = await client.contacts.get(); console.log(`Retrieved ${contacts?.length || 0} contacts`); // Access other modules const organization = await client.organization.get(); const departments = await client.departments.get(); const agents = await client.agents.get(); } catch (error) { if (error instanceof ZohoApiError) { console.error("API Error:", error.responseStatusCode, error.message); } else if (error instanceof SDKException) { console.error("SDK Error:", error.code, error.message); } else { console.error("Unknown error:", error); } } } main(); ``` ### Response N/A (This is a client-side SDK usage example, not a direct API response) ### Error Handling - **SDK_UNINITIALIZATION_ERROR**: Thrown if `createDeskClient()` is called before initialization. - **ZohoApiError**: Thrown on non-2xx HTTP responses from the Zoho API. Provides `responseStatusCode`, `errorCode`, and `message`. - **SDKException**: General SDK errors, providing `code` and `message`. ``` -------------------------------- ### Complete Zoho Desk Node.js SDK Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/client-factory.md A comprehensive example covering SDK initialization, client creation, and making API calls to fetch tickets, contacts, organization, departments, and agents. ```typescript import { InitializeBuilder, OAuthBuilder, createDeskClient, LogBuilder, Levels, SDKConfigBuilder, USDataCenter, ZohoApiError, SDKException, } from "@banana.inc/zoho-desk-nodejs-sdk"; async function main() { try { // Step 1: Build token const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); // Step 2: Configure SDK const logger = new LogBuilder() .level(Levels.INFO) .filePath("./sdk.log") .build(); const config = new SDKConfigBuilder() .timeout(30000) .maxRetries(3) .build(); // Step 3: Initialize await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .logger(logger) .SDKConfig(config) .initialize(); // Step 4: Create client const client = createDeskClient(); // Step 5: Use API modules console.log("Fetching tickets..."); const tickets = await client.tickets.get(); console.log(`Retrieved ${tickets?.length || 0} tickets`); console.log("Fetching contacts..."); const contacts = await client.contacts.get(); console.log(`Retrieved ${contacts?.length || 0} contacts`); // Access other modules const organization = await client.organization.get(); const departments = await client.departments.get(); const agents = await client.agents.get(); } catch (error) { if (error instanceof ZohoApiError) { console.error("API Error:", error.responseStatusCode, error.message); } else if (error instanceof SDKException) { console.error("SDK Error:", error.code, error.message); } else { console.error("Unknown error:", error); } } } main(); ``` -------------------------------- ### Get All Tokens Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/token-store.md Shows how to retrieve all tokens currently stored. This method might throw an SDKException if there's an error during retrieval. ```typescript const store = new FileStore("./tokens.csv"); const allTokens = await store.getTokens(); console.log(`Stored ${allTokens.length} tokens`); ``` -------------------------------- ### Client Credentials Flow Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/oauth-builder.md Example demonstrating the client credentials flow, suitable for server-to-server interactions without user context. Ensure you import OAuthBuilder. ```typescript import { OAuthBuilder } from "@banana.inc/zoho-desk-nodejs-sdk"; const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .scope("Desk.tickets.ALL") .orgId("your-org-id") .clientCredentials() .build(); ``` -------------------------------- ### Usage Pattern: Initialization and Usage Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/client-factory.md Step-by-step guide on initializing the SDK, creating a client instance, and using it to access API modules. ```APIDOC ## Usage Pattern: Initialization and Usage ### Step-by-Step Initialization and Usage ```typescript import { InitializeBuilder, OAuthBuilder, createDeskClient, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; // Step 1: Build OAuth token const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); // Step 2: Initialize SDK (must happen once before client creation) await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .initialize(); // Step 3: Create client const client = createDeskClient(); // Step 4: Use client to access modules const tickets = await client.tickets.get(); const contacts = await client.contacts.get(); ``` ``` -------------------------------- ### Install Zoho Desk Node.js SDK Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/README.md Install the SDK using npm. Requires Node.js version 18 or higher. This package is ESM-only. ```bash npm install @banana.inc/zoho-desk-nodejs-sdk ``` -------------------------------- ### Set Log File Path Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/logging.md Configures the logger to write output to a specified file. This example sets the path to './logs/sdk.log'. ```typescript new LogBuilder() .level(Levels.INFO) .filePath("./logs/sdk.log") .build(); ``` -------------------------------- ### Default Logging Initialization Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/logging.md Demonstrates initializing the SDK without explicitly setting a logger, which defaults to 'OFF' (no logging). ```typescript await new InitializeBuilder() .environment(environment) .token(token) // No logger set → defaults to Levels.OFF .initialize(); ``` -------------------------------- ### Full Authentication Example with Persistence Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/authentication.md Demonstrates building an OAuth token, initializing the SDK with a persistence store, and making an API call. Includes token revocation. ```typescript import { InitializeBuilder, OAuthBuilder, USDataCenter, FileStore, } from "@banana.inc/zoho-desk-nodejs-sdk"; // Build OAuth token const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); // Initialize with persistence store await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .store(new FileStore("./tokens.csv")) .initialize(); // SDK automatically handles token refresh on API calls import { createDeskClient } from "@banana.inc/zoho-desk-nodejs-sdk"; const client = createDeskClient(); const tickets = await client.tickets.get(); // Revoke token when done await token.revoke(USDataCenter.PRODUCTION()); ``` -------------------------------- ### FileStore Constructor Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/token-store.md Demonstrates initializing the FileStore with a path to the CSV file where tokens will be stored. The file will be created if it doesn't exist. ```typescript const store = new FileStore("./zoho_desk_tokens.csv"); ``` -------------------------------- ### Full SDK Initialization and Client Usage Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/client-factory.md This example demonstrates the complete process: building an OAuth token, initializing the SDK with environment and token details, creating the client, and then using the client to fetch data from the tickets and contacts modules. ```typescript import { InitializeBuilder, OAuthBuilder, createDeskClient, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; // Step 1: Build OAuth token const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); // Step 2: Initialize SDK (must happen once before client creation) await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .initialize(); // Step 3: Create client const client = createDeskClient(); // Step 4: Use client to access modules const tickets = await client.tickets.get(); const contacts = await client.contacts.get(); ``` -------------------------------- ### Quick Start: Initialize and Use Zoho Desk Client Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/README.md Initialize the SDK with OAuth token, data center, and token store, then create a client to call APIs. Imports include InitializeBuilder, OAuthBuilder, USDataCenter, FileStore, and createDeskClient. ```typescript import { InitializeBuilder, OAuthBuilder, USDataCenter, FileStore, createDeskClient, } from "@banana.inc/zoho-desk-nodejs-sdk"; // 1. Build the OAuth token const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); // 2. Initialize the SDK await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .store(new FileStore("./tokens.csv")) .initialize(); // 3. Create the client and call APIs const client = createDeskClient(); const tickets = await client.tickets.get(); ``` -------------------------------- ### Complete PKCE Flow Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/pkce.md Demonstrates the end-to-end PKCE flow, from generating a PKCE pair to building the authorization URL and exchanging the authorization code with the verifier. ```APIDOC ## Complete PKCE Flow ### Step-by-Step 1. **Generate PKCE pair** — Random verifier and computed challenge 2. **Build authorization URL** — Include challenge in authorization request 3. **User authorizes** — Receives authorization code 4. **Exchange code with verifier** — Prove ownership of verifier used in step 2 ```typescript import { generatePKCEPair, AuthorizationUrlBuilder, OAuthBuilder, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; // Step 1: Generate PKCE pair const pkce = await generatePKCEPair(); // Step 2: Build authorization URL with challenge const authUrl = new AuthorizationUrlBuilder() .clientId("your-client-id") .scope("Desk.tickets.ALL") .redirectUri("https://your-app.com/oauth/callback") .pkce(pkce) .build(USDataCenter.PRODUCTION()); console.log(`Redirect user to: ${authUrl}`); // User authorizes and is redirected to: // https://your-app.com/oauth/callback?code=AUTH_CODE&state=STATE // Step 3: Handle callback and build token with verifier const authCode = "AUTH_CODE"; // from query param const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .grantToken(authCode) .redirectURL("https://your-app.com/oauth/callback") .codeVerifier(pkce.codeVerifier) // Include verifier from step 1 .build(); // Token now has verifier set; it will be sent with token exchange request ``` ``` -------------------------------- ### API Client Access Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/README.md Shows how to access the various API modules after the SDK has been initialized. It demonstrates fetching ticket data using the client. ```APIDOC ## API Client Access ### Description Accesses the lazily loaded API modules through the `createDeskClient` function after SDK initialization. ### Method `createDeskClient()` and subsequent module access (e.g., `client.tickets.get()`) ### Parameters None directly for `createDeskClient()`. Module methods may have parameters. ### Request Example ```typescript import { createDeskClient } from '@banana.inc/zoho-desk-nodejs-sdk'; const client = createDeskClient(); // Example: Fetching tickets const tickets = await client.tickets.get(); console.log(tickets); ``` ### Response - **ZohoDeskClient**: An object providing access to all available API modules. - **Module Methods**: Responses vary based on the specific API module and method called (e.g., `client.tickets.get()` returns a list of tickets). ``` -------------------------------- ### Save Token Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/token-store.md Illustrates how to save or update a token in the store. This operation may throw an SDKException on failure. ```typescript const store = new FileStore("./tokens.csv"); const token = new OAuthBuilder() .clientId("id") .clientSecret("secret") .refreshToken("refresh-token") .build(); await store.saveToken(token); ``` -------------------------------- ### Refresh Token Flow Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/oauth-builder.md Example demonstrating the refresh token flow. This flow is suitable for server-side applications requiring long-lived tokens. Ensure you import OAuthBuilder. ```typescript import { OAuthBuilder } from "@banana.inc/zoho-desk-nodejs-sdk"; const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); ``` -------------------------------- ### Complete PKCE Flow Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/pkce.md Demonstrates the full PKCE flow: generating a pair, building an authorization URL with the challenge, and then exchanging the authorization code for a token using the verifier. This ensures secure authorization for public clients. ```typescript import { generatePKCEPair, AuthorizationUrlBuilder, OAuthBuilder, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; // Step 1: Generate PKCE pair const pkce = await generatePKCEPair(); // Step 2: Build authorization URL with challenge const authUrl = new AuthorizationUrlBuilder() .clientId("your-client-id") .scope("Desk.tickets.ALL") .redirectUri("https://your-app.com/oauth/callback") .pkce(pkce) .build(USDataCenter.PRODUCTION()); console.log(`Redirect user to: ${authUrl}`); // User authorizes and is redirected to: // https://your-app.com/oauth/callback?code=AUTH_CODE&state=STATE // Step 3: Handle callback and build token with verifier const authCode = "AUTH_CODE"; // from query param const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .grantToken(authCode) .redirectURL("https://your-app.com/oauth/callback") .codeVerifier(pkce.codeVerifier) // Include verifier from step 1 .build(); // Token now has verifier set; it will be sent with token exchange request ``` -------------------------------- ### Custom TokenStore Interface Implementation Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/token-store.md Provides an example implementation of the `TokenStore` interface for custom storage solutions like databases. ```APIDOC ## Custom Token Store Implementation To store tokens in a database, Redis, encrypted vault, etc., implement the `TokenStore` interface: ```typescript import type { TokenStore, Token } from "@banana.inc/zoho-desk-nodejs-sdk"; class DatabaseTokenStore implements TokenStore { constructor(private db: Database) {} async findToken(token: Token): Promise { const clientId = token.getClientId(); const refreshToken = token.getRefreshToken(); if (!clientId) return null; const row = await this.db.query( "SELECT * FROM tokens WHERE client_id = ? AND refresh_token = ?", [clientId, refreshToken] ); if (!row) return null; // Reconstruct OAuthToken from row... return new OAuthToken({ clientId: row.client_id, clientSecret: row.client_secret, // ... etc }); } async findTokenById(id: string): Promise { const row = await this.db.query( "SELECT * FROM tokens WHERE id = ?", [id] ); if (!row) return null; // Reconstruct OAuthToken from row... return new OAuthToken({ clientId: row.client_id, // ... etc }); } async saveToken(token: Token): Promise { const id = token.getId() || generateId(); await this.db.query( `INSERT INTO tokens (id, client_id, refresh_token, access_token, expiry_time) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE access_token = ?, expiry_time = ?`, [ id, token.getClientId(), token.getRefreshToken(), token.getAccessToken(), token.getExpiresIn(), token.getAccessToken(), token.getExpiresIn(), ] ); if (!token.getId()) { token.setId(id); } } async deleteToken(id: string): Promise { await this.db.query("DELETE FROM tokens WHERE id = ?", [id]); } async getTokens(): Promise { const rows = await this.db.query("SELECT * FROM tokens"); return rows.map(row => new OAuthToken({ clientId: row.client_id, // ... reconstruct each token })); } async deleteTokens(): Promise { await this.db.query("DELETE FROM tokens"); } } ``` ``` -------------------------------- ### Delete All Tokens Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/token-store.md Illustrates how to clear all tokens from the store. This operation can result in an SDKException if it fails. ```typescript const store = new FileStore("./tokens.csv"); await store.deleteTokens(); ``` -------------------------------- ### Initialize with OAuth Token Configuration Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/configuration.md Configures OAuth 2.0 authentication for the SDK. This example demonstrates using a refresh token, which is suitable for server-side applications. ```typescript const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); new InitializeBuilder() .token(token) .initialize(); ``` -------------------------------- ### Build Logger Instance Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/logging.md Constructs a Logger instance with specified level and file path. This logger can then be used for SDK operations. ```typescript const logger = new LogBuilder() .level(Levels.DEBUG) .filePath("./sdk.log") .build(); ``` -------------------------------- ### SDK Initialization with Custom Logger Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/logging.md Shows how to configure and pass a custom logger to the InitializeBuilder for SDK operations. This example sets up DEBUG level logging to './sdk.log'. ```typescript import { InitializeBuilder, OAuthBuilder, LogBuilder, Levels, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; const token = new OAuthBuilder() .clientId("id") .clientSecret("secret") .refreshToken("refresh-token") .build(); const logger = new LogBuilder() .level(Levels.DEBUG) .filePath("./sdk.log") .build(); await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .logger(logger) .initialize(); ``` -------------------------------- ### PKCE Flow Setup Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/authorization-url.md Sets up the PKCE flow for secure public clients by generating a PKCE pair, building the authorization URL with it, and then exchanging the authorization code with the verifier. Requires client ID, client secret, and the generated PKCE verifier. ```typescript import { AuthorizationUrlBuilder, OAuthBuilder, generatePKCEPair, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; // Step 1: Generate PKCE pair const pkce = await generatePKCEPair(); // Step 2: Build authorization URL with PKCE const authUrl = new AuthorizationUrlBuilder() .clientId("your-client-id") .scope("Desk.tickets.ALL") .redirectUri("https://your-app.com/oauth/callback") .pkce(pkce) .build(USDataCenter.PRODUCTION()); // Redirect user... // Step 3: Exchange code with verifier const authorizationCode = "..."; const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .grantToken(authorizationCode) .redirectURL("https://your-app.com/oauth/callback") .codeVerifier(pkce.codeVerifier) .build(); ``` -------------------------------- ### Authorization Code Flow Setup Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/authorization-url.md Sets up the authorization code flow by first building the authorization URL and then handling the redirect callback to build the token. Requires client ID, client secret, and the authorization code from the callback. ```typescript import { AuthorizationUrlBuilder, OAuthBuilder, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; // Step 1: Build authorization URL const authUrl = new AuthorizationUrlBuilder() .clientId("your-client-id") .scope("Desk.tickets.ALL") .redirectUri("https://your-app.com/oauth/callback") .state(crypto.randomBytes(16).toString("hex")) .build(USDataCenter.PRODUCTION()); // Redirect user to authUrl... // Step 2: Handle redirect callback and build token const authorizationCode = "..."; // from callback query param const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .grantToken(authorizationCode) .redirectURL("https://your-app.com/oauth/callback") .build(); ``` -------------------------------- ### Implicit Flow Setup Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/authorization-url.md Sets up the implicit flow by building an authorization URL with response_type=token and then parsing the resulting URL fragment. This flow is not recommended for sensitive operations. ```typescript import { AuthorizationUrlBuilder, parseImplicitFragment, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; // Step 1: Build authorization URL with response_type=token const authUrl = new AuthorizationUrlBuilder() .clientId("your-client-id") .scope("Desk.tickets.ALL") .redirectUri("https://your-app.com/oauth/callback") .responseType("token") .build(USDataCenter.PRODUCTION()); // Redirect user to authUrl... // Step 2: Parse token from redirect fragment // After redirect: https://your-app.com/oauth/callback#access_token=1000.abc...&expires_in=3600 const fragment = window.location.hash.slice(1); // Remove # const token = parseImplicitFragment(fragment); ``` -------------------------------- ### Find Token Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/token-store.md Demonstrates how to find a stored token using its credentials. Ensure the OAuthBuilder is used to construct the token object. ```typescript const token = new OAuthBuilder() .clientId("id") .clientSecret("secret") .refreshToken("refresh-token") .build(); const store = new FileStore("./tokens.csv"); const found = await store.findToken(token); if (found) { console.log("Token found in store"); } ``` -------------------------------- ### Custom TokenStore Implementation Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/configuration.md Provides an example of implementing a custom token store using a database. This allows for flexible token persistence beyond the default file-based storage. ```typescript class DatabaseStore implements TokenStore { async findToken(token: Token): Promise { /* ... */ } async findTokenById(id: string): Promise { /* ... */ } async saveToken(token: Token): Promise { /* ... */ } async deleteToken(id: string): Promise { /* ... */ } async getTokens(): Promise { /* ... */ } async deleteTokens(): Promise { /* ... */ } } new InitializeBuilder() .store(new DatabaseStore()) .initialize(); ``` -------------------------------- ### Example Log Output (DEBUG level) Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/logging.md Illustrates the typical log messages generated by the SDK when operating at the DEBUG level, including initialization, token handling, API requests, and retries. ```log [INFO] Zoho Desk SDK initialized successfully. [DEBUG] Using existing access token (not expired). [DEBUG] GET /api/v1/tickets [INFO] Refreshing access token... [INFO] Access token refreshed successfully. [DEBUG] POST /api/v1/tickets with body: {...} [WARN] Request failed with status 429, retrying... [DEBUG] Retry attempt 1/3, waiting 3 seconds... ``` -------------------------------- ### Token ID Management Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/token-store.md Demonstrates how the SDK automatically generates and manages token IDs when using a custom store. The ID is assigned after the first save. ```typescript const token = new OAuthBuilder() .clientId("id") .clientSecret("secret") .refreshToken("refresh-token") .build(); console.log(token.getId()); // null (not yet saved) const store = new FileStore("./tokens.csv"); await store.saveToken(token); console.log(token.getId()); // "1" (assigned by store) // Later, retrieve by ID const found = await store.findTokenById("1"); ``` -------------------------------- ### Basic HTTP Proxy (No Authentication) Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/proxy.md Example of configuring a proxy without authentication, suitable for open or internal corporate proxies that do not require credentials. ```typescript const proxy = new ProxyBuilder() .host("proxy.internal.company.com") .port(3128) .build(); ``` -------------------------------- ### Create ZohoDeskClient Instance Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/client-factory.md Use the `createDeskClient()` factory function to get an instance of the main API client. This function should be called after the SDK has been successfully initialized. ```typescript import { createDeskClient } from "@banana.inc/zoho-desk-nodejs-sdk"; const client = createDeskClient(); ``` -------------------------------- ### IoT Device Authorization Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/device-auth.md Example for authorizing IoT devices that lack a user interface. It shows how to request a device code, display authorization details, poll for a token, and initialize the SDK with token storage. ```typescript const deviceCode = await requestDeviceCode( environment, "device-app-id", "Desk.tickets.READ", ); console.log(`Auth at: ${deviceCode.verification_url}`); console.log(`Code: ${deviceCode.user_code}`); const token = await pollForDeviceToken(environment, deviceCode, { clientId: "device-app-id", clientSecret: "device-app-secret", }); // Store token for future use await new InitializeBuilder() .environment(environment) .token(token) .store(new FileStore("./device-token.csv")) .initialize(); ``` -------------------------------- ### Get Logger Level Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/logging.md Retrieves the currently configured logging level from a Logger instance. This is useful for verifying logger settings. ```typescript const logger = new LogBuilder().level(Levels.DEBUG).build(); console.log(logger.getLevel()); // Levels.DEBUG ``` -------------------------------- ### Get Log File Path Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/logging.md Retrieves the configured log file path from a Logger instance. Returns an empty string if no path was set. ```typescript const logger = new LogBuilder().filePath("./sdk.log").build(); console.log(logger.getFilePath()); // "./sdk.log" ``` -------------------------------- ### Initialize SDK with Configuration Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/sdk-config.md Demonstrates initializing the Zoho Desk Node.js SDK with custom OAuth tokens and SDK configuration. ```typescript import { InitializeBuilder, OAuthBuilder, SDKConfigBuilder, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; const token = new OAuthBuilder() .clientId("id") .clientSecret("secret") .refreshToken("refresh-token") .build(); const config = new SDKConfigBuilder() .timeout(30000) .maxRetries(5) .retryDelay(10) .pickListValidation(false) .build(); await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .SDKConfig(config) .initialize(); ``` -------------------------------- ### Authorization Code Flow with PKCE Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/oauth-builder.md Example for the authorization code flow with Proof Key for Code Exchange (PKCE). This flow is typically used in web applications requiring user consent. It requires generating a PKCE pair and importing both OAuthBuilder and generatePKCEPair. ```typescript import { OAuthBuilder, generatePKCEPair } from "@banana.inc/zoho-desk-nodejs-sdk"; const pkce = await generatePKCEPair(); const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .grantToken("authorization-code-from-callback") .redirectURL("https://your-app.com/callback") .codeVerifier(pkce.codeVerifier) .build(); ``` -------------------------------- ### Stored Token Resumption Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/oauth-builder.md Example for resuming a previously persisted token using its ID. This is useful for re-authenticating without going through the full OAuth flow again. Ensure you import OAuthBuilder. ```typescript import { OAuthBuilder } from "@banana.inc/zoho-desk-nodejs-sdk"; const token = new OAuthBuilder() .id("stored-token-id-from-persistence-layer") .build(); ``` -------------------------------- ### Initialize and Use Zoho Desk Node.js SDK Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/README.md Demonstrates the typical flow for initializing the SDK with OAuth, configuring optional settings like timeouts and logging, and then creating a client to make API calls. Includes basic error handling for API requests. ```typescript import { InitializeBuilder, OAuthBuilder, createDeskClient, USDataCenter, Levels, LogBuilder, SDKConfigBuilder, } from "@banana.inc/zoho-desk-nodejs-sdk"; // 1. Build OAuth token const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); // 2. Configure SDK (optional) const config = new SDKConfigBuilder() .timeout(30000) .maxRetries(5) .build(); const logger = new LogBuilder() .level(Levels.DEBUG) .filePath("./sdk.log") .build(); // 3. Initialize SDK (once per process) await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .SDKConfig(config) .logger(logger) .initialize(); // 4. Create client const client = createDeskClient(); // 5. Use API modules try { const tickets = await client.tickets.get(); console.log(`Retrieved ${tickets.length} tickets`); } catch (error) { console.error("API error:", error.message); } ``` -------------------------------- ### Complete Zoho Desk SDK Initialization Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/configuration.md Demonstrates the full initialization process of the Zoho Desk Node.js SDK, including OAuth token, SDK configuration, logger, token store, and optional proxy. ```typescript import { InitializeBuilder, OAuthBuilder, SDKConfigBuilder, LogBuilder, Levels, ProxyBuilder, FileStore, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; // Step 1: OAuth Token const token = new OAuthBuilder() .clientId(process.env.ZOHO_CLIENT_ID || "") .clientSecret(process.env.ZOHO_CLIENT_SECRET || "") .refreshToken(process.env.ZOHO_REFRESH_TOKEN || "") .build(); // Step 2: SDK Configuration const config = new SDKConfigBuilder() .autoRefreshFields(false) .pickListValidation(true) .timeout(30000) // 30 second timeout .maxRetries(5) // Retry up to 5 times .retryDelay(3) // 3 seconds between retries .build(); // Step 3: Logger Configuration const logger = new LogBuilder() .level(process.env.NODE_ENV === "production" ? Levels.WARN : Levels.DEBUG) .filePath(process.env.LOG_FILE || "./sdk.log") .build(); // Step 4: Token Store const store = new FileStore(process.env.TOKEN_STORE_PATH || "./tokens.csv"); // Step 5: Proxy Configuration (if needed) let proxy; if (process.env.PROXY_HOST) { proxy = new ProxyBuilder() .host(process.env.PROXY_HOST) .port(parseInt(process.env.PROXY_PORT || "8080", 10)) .user(process.env.PROXY_USER) .password(process.env.PROXY_PASS) .build(); } // Step 6: Initialize await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .store(store) .SDKConfig(config) .logger(logger) .requestProxy(proxy) .initialize(); // Step 7: Create client import { createDeskClient } from "@banana.inc/zoho-desk-nodejs-sdk"; const client = createDeskClient(); ``` -------------------------------- ### SDK Lifecycle Steps Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/README.md Illustrates the sequence of operations for initializing and using the Zoho Desk Node.js SDK, from instantiation of builders to accessing modules and handling errors. ```text 1. Instantiate builders (OAuthBuilder, SDKConfigBuilder, LogBuilder, ProxyBuilder) ↓ 2. Call InitializeBuilder with environment, token, and optional config ↓ 3. Call InitializeBuilder.initialize() to set up singleton Initializer ↓ 4. Call createDeskClient() to get ZohoDeskClient instance ↓ 5. Access 126 modules via client getters (lazy-loaded on first access) ↓ 6. Call methods on modules (async API calls) ↓ 7. Errors caught as SDKException or ZohoApiError ``` -------------------------------- ### Retry Behavior Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/sdk-config.md Configure the number of retries and the delay between them for transient failures. ```typescript // Will retry up to 5 times with 10 second delay new SDKConfigBuilder() .maxRetries(5) .retryDelay(10) .build(); ``` -------------------------------- ### Initialize SDK with Proxy Configuration Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/proxy.md Demonstrates how to initialize the Zoho Desk Node.js SDK with a configured proxy. Ensure all necessary imports are included. ```typescript import { InitializeBuilder, OAuthBuilder, ProxyBuilder, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; const token = new OAuthBuilder() .clientId("id") .clientSecret("secret") .refreshToken("refresh-token") .build(); const proxy = new ProxyBuilder() .host("proxy.example.com") .port(8080) .user("proxy-user") .password("proxy-pass") .build(); await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .requestProxy(proxy) .initialize(); ``` -------------------------------- ### Get Proxy Hostname Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/proxy.md Retrieves the configured proxy hostname from a RequestProxy instance. ```typescript const proxy = new ProxyBuilder().host("proxy.example.com").port(8080).build(); console.log(proxy.getHost()); // "proxy.example.com" ``` -------------------------------- ### Get Proxy Port Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/proxy.md Retrieves the configured proxy port number from a RequestProxy instance. ```typescript const proxy = new ProxyBuilder().host("proxy.example.com").port(8080).build(); console.log(proxy.getPort()); // 8080 ``` -------------------------------- ### Complete SDK Initialization with Logging Configuration Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/logging.md Shows a full SDK initialization process, including setting up OAuth, configuring logging to a file, defining SDK configurations like timeout and retries, and initializing the client. All SDK operations will be logged to the specified file. ```typescript import { InitializeBuilder, OAuthBuilder, LogBuilder, Levels, SDKConfigBuilder, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); const logger = new LogBuilder() .level(Levels.DEBUG) .filePath("./sdk.log") .build(); const config = new SDKConfigBuilder() .timeout(30000) .maxRetries(5) .build(); await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .logger(logger) .SDKConfig(config) .initialize(); import { createDeskClient } from "@banana.inc/zoho-desk-nodejs-sdk"; const client = createDeskClient(); // All SDK operations are now logged to ./sdk.log const tickets = await client.tickets.get(); ``` -------------------------------- ### Get Proxy Password Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/proxy.md Retrieves the configured proxy password from a RequestProxy instance, or null if not set. ```typescript const proxy = new ProxyBuilder() .host("proxy.example.com") .port(8080) .password("secret") .build(); console.log(proxy.getPassword()); // "secret" ``` -------------------------------- ### Get Proxy Username Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/proxy.md Retrieves the configured proxy username from a RequestProxy instance, or null if not set. ```typescript const proxy = new ProxyBuilder() .host("proxy.example.com") .port(8080) .user("john") .build(); console.log(proxy.getUser()); // "john" ``` -------------------------------- ### Timeout Behavior Examples Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/sdk-config.md Configure the timeout for individual HTTP requests. A value of 0 means no timeout. ```typescript // Request aborts after 30 seconds new SDKConfigBuilder() .timeout(30000) .build(); ``` ```typescript // No timeout new SDKConfigBuilder() .timeout(0) .build(); ``` -------------------------------- ### Usage in Initialization Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/proxy.md Demonstrates how to integrate proxy configuration when initializing the Zoho Desk Node.js SDK. ```APIDOC ## InitializeBuilder with RequestProxy ### Description Shows how to use `ProxyBuilder` to create a `RequestProxy` object and pass it to the `InitializeBuilder`. ### Method `InitializeBuilder.requestProxy(proxy: RequestProxy) ` ### Example ```typescript import { InitializeBuilder, OAuthBuilder, ProxyBuilder, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; const token = new OAuthBuilder() .clientId("id") .clientSecret("secret") .refreshToken("refresh-token") .build(); const proxy = new ProxyBuilder() .host("proxy.example.com") .port(8080) .user("proxy-user") .password("proxy-pass") .build(); await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .requestProxy(proxy) .initialize(); ``` --- ## Basic HTTP Proxy (No Auth) ### Description Example of configuring a basic HTTP proxy without authentication. ### Method `ProxyBuilder` ### Example ```typescript const proxy = new ProxyBuilder() .host("proxy.internal.company.com") .port(3128) .build(); ``` --- ``` -------------------------------- ### Delete Token Example Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/token-store.md Demonstrates removing a token from the store using its ID. This operation can throw an SDKException if it fails. ```typescript const store = new FileStore("./tokens.csv"); await store.deleteToken("stored-token-123"); ``` -------------------------------- ### Initialize SDK with US Production Data Center Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/data-centers.md Demonstrates how to initialize the Zoho Desk Node.js SDK using the US production data center and OAuth token. Ensure you have the necessary imports. ```typescript import { InitializeBuilder, OAuthBuilder, USDataCenter, } from "@banana.inc/zoho-desk-nodejs-sdk"; const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .initialize(); ``` -------------------------------- ### Initialize Zoho Desk Node.js SDK Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/initialize-builder.md This snippet demonstrates the typical pattern for initializing the Zoho Desk Node.js SDK. It includes building an OAuth token, configuring SDK options like timeout and retries, setting up a logger, and finally initializing the SDK with a specified environment and token store. ```typescript import { InitializeBuilder, OAuthBuilder, USDataCenter, FileStore, SDKConfigBuilder, Levels, LogBuilder, } from "@banana.inc/zoho-desk-nodejs-sdk"; // Step 1: Build OAuth token const token = new OAuthBuilder() .clientId("your-client-id") .clientSecret("your-client-secret") .refreshToken("your-refresh-token") .build(); // Step 2: Configure SDK options const config = new SDKConfigBuilder() .timeout(30000) .maxRetries(5) .build(); const logger = new LogBuilder() .level(Levels.DEBUG) .filePath("./sdk.log") .build(); // Step 3: Initialize SDK await new InitializeBuilder() .environment(USDataCenter.PRODUCTION()) .token(token) .store(new FileStore("./tokens.csv")) .SDKConfig(config) .logger(logger) .initialize(); // Step 4: Create client and make calls import { createDeskClient } from "@banana.inc/zoho-desk-nodejs-sdk"; const client = createDeskClient(); const tickets = await client.tickets.get(); ``` -------------------------------- ### JPDataCenter Source: https://github.com/dragonxsx/zoho-desk-nodejs-sdk/blob/main/_autodocs/api-reference/data-centers.md Represents the Japan data center. Provides a static PRODUCTION() method to get a configured Environment object. ```APIDOC ## JPDataCenter ### Description Represents the Japan data center configuration for the Zoho Desk Node.js SDK. It provides access to region-specific API and OAuth endpoints. ### Class `JPDataCenter` ### Methods #### static PRODUCTION(): Environment Returns an `Environment` object configured with production endpoints for the JP region. **API Base URL:** `https://desk.zoho.jp` **OAuth URL:** `https://accounts.zoho.jp/oauth/v2/token` ### Example ```typescript import { JPDataCenter } from "@banana.inc/zoho-desk-nodejs-sdk"; const environment = JPDataCenter.PRODUCTION(); ``` ```