JavaScript Integration Guide
Complete guide to integrating Astro-Fusion API with JavaScript applications
Setup & Installation
CDN (Browser)
For client-side JavaScript applications
<script src="https://cdn.jsdelivr.net/npm/@astrofusion/api-client@latest/dist/browser.js"></script>
NPM/Yarn
For Node.js applications and bundlers
npm install @astrofusion/api-client
# or
yarn add @astrofusion/api-client
Environment Configuration
// .env
ASTROFUSION_API_KEY=your_api_key_here
ASTROFUSION_BASE_URL=https://api.astro-fusion.com/v1
Basic Usage
Initialize the Client
// Browser - using CDN
const astroClient = new AstroFusionAPI({
apiKey: 'your_api_key_here',
baseURL: 'https://api.astro-fusion.com/v1'
});
// Browser - using ES modules
import { AstroFusionAPI } from 'https://cdn.jsdelivr.net/npm/@astrofusion/api-client@latest/dist/browser.js';
const astroClient = new AstroFusionAPI({
apiKey: 'your_api_key_here'
});
// Node.js - CommonJS
const { AstroFusionAPI } = require('@astrofusion/api-client');
const astroClient = new AstroFusionAPI({
apiKey: process.env.ASTROFUSION_API_KEY,
baseURL: process.env.ASTROFUSION_BASE_URL
});
// Node.js - ES Modules
import { AstroFusionAPI } from '@astrofusion/api-client';
const astroClient = new AstroFusionAPI({
apiKey: process.env.ASTROFUSION_API_KEY
});
Get Panchanga (Calendar)
async function getDailyPanchanga(date, latitude, longitude) {
try {
const panchanga = await astroClient.panchanga.get({
date: date.toISOString(),
latitude: latitude,
longitude: longitude,
timezone: 5.75 // Nepal timezone
});
console.log('Tithi:', panchanga.tithi.name);
console.log('Nakshatra:', panchanga.nakshatra.name);
console.log('Yoga:', panchanga.yoga.name);
console.log('Karana:', panchanga.karana.name);
return panchanga;
} catch (error) {
console.error('Error fetching Panchanga:', error.message);
throw error;
}
}
// Usage
const today = new Date();
getDailyPanchanga(today, 27.7172, 85.3240)
.then(data => console.log('Panchanga data:', data))
.catch(error => console.error('Failed:', error));
Calculate Birth Chart
async function calculateBirthChart(birthData) {
try {
const kundali = await astroClient.kundali.calculate(birthData);
console.log('Ascendant:', kundali.ascendant.sign);
console.log('Moon Sign:', kundali.moonSign.sign);
console.log('Sun Sign:', kundali.sunSign.sign);
// Display planetary positions
kundali.planets.forEach(planet => {
console.log(\`\${planet.name}: \${planet.sign} \${planet.degrees}°\`);
});
return kundali;
} catch (error) {
console.error('Error calculating birth chart:', error.message);
throw error;
}
}
// Example birth data
const birthData = {
date: '1990-06-15T14:30:00Z',
latitude: 28.6139,
longitude: 77.2090,
timezone: 5.5,
name: 'John Doe'
};
calculateBirthChart(birthData)
.then(chart => console.log('Birth chart:', chart))
.catch(error => console.error('Failed:', error));
Advanced Examples
Marriage Compatibility Analysis
class MarriageCompatibility {
constructor(astroClient) {
this.client = astroClient;
}
async analyzeCompatibility(groomData, brideData) {
try {
const result = await this.client.compatibility.match({
boy: groomData,
girl: brideData,
system: 'ashtakoot',
includeRemedies: true,
detailedReport: true
});
return {
overallScore: result.compatibility.percentage,
result: result.compatibility.result,
ashtakootScore: result.ashtakoot,
manglikStatus: result.manglik,
remedies: result.remedies
};
} catch (error) {
console.error('Compatibility analysis failed:', error);
throw error;
}
}
generateReport(analysis) {
const report = {
summary: \`Compatibility Score: \${analysis.overallScore}%\`,
recommendation: analysis.result,
concerns: [],
remedies: []
};
// Check for Nadi dosha
const nadiScore = analysis.ashtakoot.nadi?.score || 8;
if (nadiScore === 0) {
report.concerns.push('Nadi dosha present');
report.remedies.push(...analysis.remedies.nadiDosha);
}
// Check Manglik status
if (analysis.manglik.girl.isManglik) {
report.concerns.push('Bride has Manglik dosha');
report.remedies.push(...analysis.remedies.manglikDosha);
}
return report;
}
}
// Usage
const compatibility = new MarriageCompatibility(astroClient);
const groom = {
date: '1990-06-15T14:30:00Z',
latitude: 28.6139,
longitude: 77.2090,
timezone: 5.5,
name: 'Rahul Sharma'
};
const bride = {
date: '1992-03-22T10:15:00Z',
latitude: 27.7172,
longitude: 85.3240,
timezone: 5.75,
name: 'Priya Thapa'
};
compatibility.analyzeCompatibility(groom, bride)
.then(analysis => {
const report = compatibility.generateReport(analysis);
console.log('Compatibility Report:', report);
})
.catch(error => console.error('Analysis failed:', error));
Horoscope Widget Component
class HoroscopeWidget {
constructor(containerId, astroClient) {
this.container = document.getElementById(containerId);
this.client = astroClient;
this.currentSign = 'aries';
this.init();
}
init() {
this.render();
this.attachEventListeners();
this.loadHoroscope();
}
render() {
this.container.innerHTML = \`
<div class="horoscope-widget">
<select id="zodiac-select" class="zodiac-dropdown">
<option value="aries">♈ Aries</option>
<option value="taurus">♉ Taurus</option>
<option value="gemini">♊ Gemini</option>
<option value="cancer">♋ Cancer</option>
<option value="leo">♌ Leo</option>
<option value="virgo">♍ Virgo</option>
<option value="libra">♎ Libra</option>
<option value="scorpio">♏ Scorpio</option>
<option value="sagittarius">♐ Sagittarius</option>
<option value="capricorn">♑ Capricorn</option>
<option value="aquarius">♒ Aquarius</option>
<option value="pisces">♓ Pisces</option>
</select>
<div id="horoscope-content" class="horoscope-content">
<div class="loading">Loading horoscope...</div>
</div>
</div>
\`;
}
attachEventListeners() {
const select = this.container.querySelector('#zodiac-select');
select.addEventListener('change', (e) => {
this.currentSign = e.target.value;
this.loadHoroscope();
});
}
async loadHoroscope() {
const contentDiv = this.container.querySelector('#horoscope-content');
try {
contentDiv.innerHTML = '<div class="loading">Loading...</div>';
const horoscope = await this.client.horoscope.getDaily(this.currentSign);
contentDiv.innerHTML = \`
<h3>\${horoscope.sign} Daily Horoscope</h3>
<p class="prediction">\${horoscope.prediction}</p>
<div class="lucky-elements">
<div class="lucky-item">
<strong>Lucky Number:</strong> \${horoscope.lucky.number}
</div>
<div class="lucky-item">
<strong>Lucky Color:</strong> \${horoscope.lucky.color}
</div>
<div class="lucky-item">
<strong>Lucky Stone:</strong> \${horoscope.lucky.stone}
</div>
</div>
<div class="remedies">
<h4>Recommended Remedies</h4>
<ul>
\${horoscope.remedies.map(remedy => \`<li>\${remedy}</li>\`).join('')}
</ul>
</div>
\`;
} catch (error) {
contentDiv.innerHTML = \`
<div class="error">
Failed to load horoscope: \${error.message}
</div>
\`;
}
}
}
// Usage
document.addEventListener('DOMContentLoaded', () => {
const astroClient = new AstroFusionAPI({
apiKey: 'your_api_key_here'
});
new HoroscopeWidget('horoscope-container', astroClient);
});
Error Handling & Best Practices
Rate Limiting
class RateLimitedClient {
constructor(astroClient, requestsPerHour = 100) {
this.client = astroClient;
this.requestsPerHour = requestsPerHour;
this.requests = [];
}
async makeRequest(endpoint, params) {
this.cleanOldRequests();
if (this.requests.length >= this.requestsPerHour) {
const oldestRequest = this.requests[0];
const waitTime = 3600000 - (Date.now() - oldestRequest); // 1 hour
if (waitTime > 0) {
throw new Error(\`Rate limit exceeded. Wait \${Math.ceil(waitTime / 1000)} seconds\`);
}
}
try {
const result = await this.client[endpoint](params);
this.requests.push(Date.now());
return result;
} catch (error) {
if (error.status === 429) {
throw new Error('API rate limit exceeded');
}
throw error;
}
}
cleanOldRequests() {
const oneHourAgo = Date.now() - 3600000;
this.requests = this.requests.filter(timestamp => timestamp > oneHourAgo);
}
}
Retry Logic
async function withRetry(fn, maxRetries = 3, delay = 1000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxRetries || !isRetryableError(error)) {
throw error;
}
console.warn(\`Attempt \${attempt} failed, retrying in \${delay}ms...\`, error.message);
await new Promise(resolve => setTimeout(resolve, delay));
delay *= 2; // Exponential backoff
}
}
}
function isRetryableError(error) {
// Retry on network errors, 5xx server errors, or rate limiting
return (
error.code === 'NETWORK_ERROR' ||
error.code === 'TIMEOUT' ||
(error.status >= 500 && error.status < 600) ||
error.status === 429
);
}
// Usage
const panchanga = await withRetry(() =>
astroClient.panchanga.get({
date: '2026-02-26T12:00:00Z',
latitude: 27.7172,
longitude: 85.3240
})
);
Data Caching
class CachedAstroClient {
constructor(astroClient, cacheDuration = 3600000) { // 1 hour default
this.client = astroClient;
this.cache = new Map();
this.cacheDuration = cacheDuration;
}
async getCached(endpoint, params, cacheKey) {
const key = cacheKey || this.generateCacheKey(endpoint, params);
// Check cache
const cached = this.cache.get(key);
if (cached && (Date.now() - cached.timestamp) < this.cacheDuration) {
return cached.data;
}
// Fetch fresh data
const data = await this.client[endpoint](params);
// Cache the result
this.cache.set(key, {
data: data,
timestamp: Date.now()
});
// Clean old cache entries periodically
if (this.cache.size > 100) {
this.cleanCache();
}
return data;
}
generateCacheKey(endpoint, params) {
return \`\${endpoint}:\${JSON.stringify(params)}\`;
}
cleanCache() {
const cutoff = Date.now() - this.cacheDuration;
for (const [key, value] of this.cache.entries()) {
if (value.timestamp < cutoff) {
this.cache.delete(key);
}
}
}
}
// Usage
const cachedClient = new CachedAstroClient(astroClient);
// Panchanga data is cached for 1 hour
const panchanga = await cachedClient.getCached(
'panchanga.get',
{ date: '2026-02-26T12:00:00Z', latitude: 27.7172, longitude: 85.3240 },
'panchanga_today'
);