UNPKG

astrobaba-astro-engine-sdk

Version:

Official Node.js SDK for AstroBaba Astro Engine - Professional Vedic Astrology API with automatic retry logic and comprehensive error handling

553 lines (406 loc) 14.1 kB
# @astrobaba/astro-engine-sdk [![npm version](https://img.shields.io/npm/v/@astrobaba/astro-engine-sdk.svg)](https://www.npmjs.com/package/@astrobaba/astro-engine-sdk) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) Professional Node.js SDK for AstroBaba Astro Engine - Complete Vedic Astrology API Client with automatic retry logic and exponential backoff. ## Features ✨ **Complete API Coverage** - All 11+ endpoint groups supported 🔄 **Automatic Retries** - Built-in exponential backoff for 5xx errors and network failures ⚡ **TypeScript Support** - Full type definitions included 🛡️ **Error Handling** - Clean error formatting with detailed messages ⏱️ **Configurable Timeouts** - Customizable request timeouts (default: 10s) 🎯 **Production Ready** - Battle-tested with comprehensive error handling ## Installation ```bash npm install @astrobaba/astro-engine-sdk ``` or with Yarn: ```bash yarn add @astrobaba/astro-engine-sdk ``` ## Quick Start ```javascript const AstroEngineClient = require('@astrobaba/astro-engine-sdk'); // Initialize the client (uses localhost:8000 by default) const client = new AstroEngineClient({ // baseUrl: 'http://localhost:8000/api/v1', // Default - can be omitted timeout: 10000, // 10 seconds maxRetries: 3, // Retry failed requests 3 times retryDelay: 1000, // Start with 1s delay backoffFactor: 2 // Double delay on each retry }); // Example: Get birth chart const birthData = { name: 'John Doe', date: '1990-01-15', time: '14:30:00', latitude: 28.6139, longitude: 77.2090, timezone: 'Asia/Kolkata' }; async function getBirthChart() { try { const chart = await client.birthChart(birthData); console.log('Birth Chart:', chart); } catch (error) { console.error('Error:', error.message); } } getBirthChart(); ``` ## Configuration Options ```javascript const client = new AstroEngineClient({ baseUrl: 'http://localhost:8000/api/v1', // API base URL (default) timeout: 10000, // Request timeout (ms) maxRetries: 3, // Max retry attempts retryDelay: 1000, // Initial retry delay (ms) backoffFactor: 2 // Exponential backoff multiplier }); ``` ### Retry Logic The SDK automatically retries failed requests with exponential backoff for: - **Network errors** (no response) - **5xx server errors** (500, 502, 503, 504) - **429 Too Many Requests** Retry delays: 1s → 2s → 4s (with default config) ## API Reference ### Birth Chart & Planetary Positions #### `birthChart(birthData, houseSystem?)` Calculate birth chart with planetary positions and houses. ```javascript const chart = await client.birthChart({ name: 'John Doe', date: '1990-01-15', time: '14:30:00', latitude: 28.6139, longitude: 77.2090, timezone: 'Asia/Kolkata' }, 'PLACIDUS'); console.log(chart.planets); // Planetary positions console.log(chart.houses); // House cusps console.log(chart.ascendant); // Ascendant details ``` #### `planetaryPositions(birthData)` Get detailed planetary positions. ```javascript const planets = await client.planetaryPositions(birthData); ``` #### `housePositions(birthData)` Get house positions and cusps. ```javascript const houses = await client.housePositions(birthData); ``` ### Dasha System #### `vimshottariDasha(birthData, years?)` Calculate Vimshottari Dasha periods. ```javascript const dasha = await client.vimshottariDasha(birthData, 120); console.log(dasha.current_dasha); // Current Mahadasha console.log(dasha.maha_dashas); // All Mahadashas ``` #### `antardasha(mahaDashaLord, mahaDashaStart, mahaDashaYears)` Calculate Antardasha sub-periods. ```javascript const antardasha = await client.antardasha('Venus', '2020-01-01', 20); ``` ### Panchang (Vedic Calendar) #### `panchang(date, latitude, longitude, timezone?)` Get Panchang for a specific date and location. ```javascript const panchang = await client.panchang( '2024-01-15', 28.6139, 77.2090, 'Asia/Kolkata' ); console.log(panchang.tithi); // Lunar day console.log(panchang.nakshatra); // Constellation console.log(panchang.yoga); // Yoga console.log(panchang.karana); // Karana console.log(panchang.sunrise); // Sunrise time ``` ### Divisional Charts #### `divisionalChart(birthData, division)` Calculate specific divisional chart (D1, D9, D10, etc.). ```javascript const d9 = await client.divisionalChart(birthData, 'D9'); // Navamsa const d10 = await client.divisionalChart(birthData, 'D10'); // Dasamsa ``` #### `allDivisionalCharts(birthData)` Get all major divisional charts at once. ```javascript const charts = await client.allDivisionalCharts(birthData); console.log(charts.D1); // Rasi (Birth Chart) console.log(charts.D9); // Navamsa console.log(charts.D10); // Dasamsa ``` ### KP System #### `kpChart(birthData)` Calculate KP (Krishnamurti Paddhati) system chart. ```javascript const kp = await client.kpChart(birthData); console.log(kp.cusps); // House cusps with star & sub lords console.log(kp.planets); // Planets with star & sub lords ``` ### Compatibility Matching #### `ashtakootMatching(maleData, femaleData)` Calculate Ashtakoot (8-Kuta) compatibility. ```javascript const matching = await client.ashtakootMatching(maleBirthData, femaleBirthData); console.log(matching.total_points); // Total points (out of 36) console.log(matching.compatibility_percentage); // Percentage console.log(matching.ashtakoot_matching); // Detailed breakdown console.log(matching.mangal_dosha); // Manglik analysis ``` #### `kundliMatching(maleData, femaleData)` Comprehensive Kundli matching with all details. ```javascript const match = await client.kundliMatching(maleBirthData, femaleBirthData); ``` #### `quickCompatibility(maleData, femaleData)` Quick compatibility score. ```javascript const quick = await client.quickCompatibility(maleBirthData, femaleBirthData); ``` ### Yogas & Doshas #### `yogasAndDoshas(birthData)` Analyze all yogas and doshas in birth chart. ```javascript const analysis = await client.yogasAndDoshas(birthData); console.log(analysis.yogas); // Beneficial yogas console.log(analysis.doshas); // Doshas (including Mangal Dosha) ``` ### Ashtakavarga #### `ashtakavarga(birthData)` Calculate Ashtakavarga (8-point benefic system). ```javascript const ashtakavarga = await client.ashtakavarga(birthData); ``` ### Complete Horoscope #### `completeHoroscope(birthData)` Generate comprehensive horoscope report. ```javascript const horoscope = await client.completeHoroscope(birthData); ``` ### Daily Horoscope (Sun Sign) #### `dailyHoroscope(zodiacSign, date?)` Get daily horoscope for a zodiac sign. ```javascript // Today's horoscope const daily = await client.dailyHoroscope('Aries'); // Specific date const specific = await client.dailyHoroscope('Taurus', '2024-01-15'); console.log(daily.prediction); console.log(daily.lucky_number); console.log(daily.lucky_color); ``` #### `weeklyHoroscope(zodiacSign, startDate?)` Get weekly horoscope. ```javascript const weekly = await client.weeklyHoroscope('Gemini'); ``` #### `monthlyHoroscope(zodiacSign, year?, month?)` Get monthly horoscope. ```javascript // Current month const monthly = await client.monthlyHoroscope('Cancer'); // Specific month const jan2024 = await client.monthlyHoroscope('Leo', 2024, 1); ``` #### `yearlyHoroscope(zodiacSign, year?)` Get yearly horoscope. ```javascript // Current year const yearly = await client.yearlyHoroscope('Virgo'); // Specific year const year2024 = await client.yearlyHoroscope('Libra', 2024); ``` #### `allSignsDailyHoroscope(date?)` Get daily horoscope for all zodiac signs. ```javascript const allSigns = await client.allSignsDailyHoroscope(); console.log(allSigns.Aries); console.log(allSigns.Taurus); ``` ### Complete Kundli #### `kundli(birthData)` Generate complete Kundli with all details. ```javascript const kundli = await client.kundli(birthData); console.log(kundli.basic_details); // Birth info console.log(kundli.birth_chart); // Birth chart console.log(kundli.divisional_charts); // All divisional charts console.log(kundli.dasha); // Dasha periods console.log(kundli.panchang); // Panchang console.log(kundli.yogas_doshas); // Yogas & Doshas ``` #### `basicKundli(birthData)` Get basic Kundli information. ```javascript const basic = await client.basicKundli(birthData); ``` ## TypeScript Usage ```typescript import AstroEngineClient, { BirthData, AstroEngineConfig, BirthChartResponse } from '@astrobaba/astro-engine-sdk'; const config: AstroEngineConfig = { baseUrl: 'http://localhost:8000/api/v1', timeout: 10000, maxRetries: 3 }; const client = new AstroEngineClient(config); const birthData: BirthData = { name: 'John Doe', date: '1990-01-15', time: '14:30:00', latitude: 28.6139, longitude: 77.2090, timezone: 'Asia/Kolkata' }; async function getChart(): Promise<BirthChartResponse> { return await client.birthChart(birthData); } ``` ## Error Handling ```javascript try { const chart = await client.birthChart(birthData); } catch (error) { console.error('Error code:', error.code); // Error type console.error('Status:', error.status); // HTTP status console.error('Message:', error.message); // Error message console.error('Details:', error.data); // API response data } ``` ### Error Types - **`NETWORK_ERROR`** - No response from server - **`API_ERROR`** - Server returned an error response - **`REQUEST_ERROR`** - Request setup failed ## Update Configuration ```javascript // Update config at runtime (e.g., when you deploy to production) client.updateConfig({ baseUrl: 'https://api.astrobaba.com/api/v1', maxRetries: 5 }); ``` ## Complete Example ```javascript const AstroEngineClient = require('@astrobaba/astro-engine-sdk'); const client = new AstroEngineClient({ baseUrl: 'http://localhost:8000/api/v1', timeout: 10000, maxRetries: 3 }); async function generateCompleteReport() { const birthData = { name: 'Rahul Sharma', date: '1990-01-15', time: '14:30:00', latitude: 28.6139, longitude: 77.2090, timezone: 'Asia/Kolkata' }; try { // Get birth chart console.log('Fetching birth chart...'); const chart = await client.birthChart(birthData); // Get dasha periods console.log('Calculating Dasha...'); const dasha = await client.vimshottariDasha(birthData); // Get panchang console.log('Fetching Panchang...'); const panchang = await client.panchang( birthData.date, birthData.latitude, birthData.longitude ); // Get yogas and doshas console.log('Analyzing Yogas & Doshas...'); const yogas = await client.yogasAndDoshas(birthData); // Get complete kundli console.log('Generating complete Kundli...'); const kundli = await client.kundli(birthData); console.log('Report generated successfully!'); return { chart, dasha, panchang, yogas, kundli }; } catch (error) { console.error('Failed to generate report:', error.message); throw error; } } // Compatibility check async function checkCompatibility() { const male = { name: 'Rahul', date: '1990-01-15', time: '14:30:00', latitude: 28.6139, longitude: 77.2090, timezone: 'Asia/Kolkata' }; const female = { name: 'Priya', date: '1992-05-20', time: '10:15:00', latitude: 28.6139, longitude: 77.2090, timezone: 'Asia/Kolkata' }; try { const matching = await client.ashtakootMatching(male, female); console.log(`Compatibility: ${matching.compatibility_percentage}%`); console.log(`Points: ${matching.total_points}/36`); console.log(`Male Manglik: ${matching.mangal_dosha.male.present}`); console.log(`Female Manglik: ${matching.mangal_dosha.female.present}`); return matching; } catch (error) { console.error('Matching failed:', error.message); throw error; } } // Run examples generateCompleteReport(); checkCompatibility(); ``` ## Supported Zodiac Signs `Aries`, `Taurus`, `Gemini`, `Cancer`, `Leo`, `Virgo`, `Libra`, `Scorpio`, `Sagittarius`, `Capricorn`, `Aquarius`, `Pisces` ## Supported Divisional Charts - **D1** - Rasi (Birth Chart) - **D2** - Hora (Wealth) - **D3** - Drekkana (Siblings) - **D4** - Chaturthamsa (Property) - **D7** - Saptamsa (Children) - **D9** - Navamsa (Spouse) - **D10** - Dasamsa (Career) - **D12** - Dwadasamsa (Parents) - **D16** - Shodasamsa (Vehicles) - **D20** - Vimshamsa (Spirituality) - **D24** - Chaturvimshamsa (Education) - **D27** - Saptavimshamsa (Strengths/Weaknesses) - **D30** - Trimshamsa (Misfortunes) - **D40** - Khavedamsa (Auspicious/Inauspicious) - **D45** - Akshavedamsa (General Well-being) - **D60** - Shashtyamsa (All Matters) ## Requirements - Node.js >= 14.0.0 - Astro Engine API running (FastAPI backend) ## License MIT © AstroBaba ## Support For issues and feature requests, please create an issue on GitHub. ## Changelog ### v1.0.0 - Initial release - Complete API coverage for all 11+ endpoint groups - Automatic retry logic with exponential backoff - TypeScript definitions - Comprehensive documentation