diff --git a/src/index.ts b/src/index.ts index 58edb4d..0f7599d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,27 +1,45 @@ import { SwapApi } from "../generated/apis/SwapApi"; import { ConfigurationParameters, Configuration } from "../generated/runtime"; -// Define server URLs -const PUBLIC_SERVER_URL = "https://lite-api.jup.ag/swap/v1"; -const API_KEY_SERVER_URL = "https://api.jup.ag/swap/v1"; +// --- Configuration Constants --- + +// Public endpoint URL for the Jupiter Swap API (does not require an API key). +const PUBLIC_API_URL: string = "https://lite-api.jup.ag/swap/v1"; + +// Dedicated endpoint URL for API key users (often offers higher rate limits or premium features). +const AUTHENTICATED_API_URL: string = "https://api.jup.ag/swap/v1"; /** - * Creates a Jupiter API client with optional API key support - * @param config Configuration parameters - * @returns SwapApi instance + * Creates a configured Jupiter API client instance (SwapApi). + * * The client automatically switches the base URL and adds the 'x-api-key' header + * if an API key is provided in the configuration. + * * @param config Optional configuration parameters, including 'apiKey'. + * @returns A new instance of SwapApi ready for use. */ -export const createJupiterApiClient = (config?: ConfigurationParameters) => { - // Determine which server URL to use based on whether an API key is provided - const hasApiKey = config?.apiKey !== undefined; +export const createJupiterApiClient = (config?: ConfigurationParameters): SwapApi => { + // Check if an API key is explicitly provided and is a non-empty string. + const apiKey = config?.apiKey; + const hasValidApiKey = typeof apiKey === 'string' && apiKey.length > 0; + + // Determine the appropriate base path and headers based on the presence of an API key. + const basePath = hasValidApiKey ? AUTHENTICATED_API_URL : PUBLIC_API_URL; - // Create a new configuration with the appropriate base path - const configWithServer: ConfigurationParameters = { + const headers = hasValidApiKey + ? { 'x-api-key': apiKey as string } // Safely assert apiKey as string here + : undefined; + + // Create the final configuration object. + const finalConfig: ConfigurationParameters = { ...config, - basePath: hasApiKey ? API_KEY_SERVER_URL : PUBLIC_SERVER_URL, - headers: hasApiKey ? { 'x-api-key': config?.apiKey as string } : undefined + basePath: basePath, + headers: headers, + // Note: apiKey field might be kept in config for internal library use, + // but the actual header is manually constructed above. }; - - return new SwapApi(new Configuration(configWithServer)); + + // Instantiate and return the API client. + return new SwapApi(new Configuration(finalConfig)); }; +// Re-export all type and interface definitions generated by the OpenAPI tool. export * from "../generated";