File size: 12,698 Bytes
b190b45 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
/**
* نمونه کدهای استفاده از API اخبار کریپتو
* Crypto News API Client Examples in JavaScript/Node.js
*
* این فایل شامل مثالهای مختلف برای استفاده از API اخبار است
* This file contains various examples for using the News API
*/
/**
* کلاس کلاینت برای دسترسی به API اخبار
* Client class for accessing the News API
*/
class CryptoNewsClient {
/**
* @param {string} baseUrl - آدرس پایه سرور / Base URL of the server
*/
constructor(baseUrl = window.location.origin) {
this.baseUrl = baseUrl;
}
/**
* دریافت تمام اخبار
* Get all news articles
*
* @param {number} limit - تعداد نتایج / Number of results
* @returns {Promise<Array>} آرایه مقالات / Array of articles
*
* @example
* const client = new CryptoNewsClient();
* const articles = await client.getAllNews(50);
* console.log(`Found ${articles.length} articles`);
*/
async getAllNews(limit = 100) {
try {
const url = `${this.baseUrl}/api/news?limit=${limit}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
return data.articles || [];
} catch (error) {
console.error('خطا در دریافت اخبار / Error fetching news:', error);
return [];
}
}
/**
* دریافت اخبار بر اساس احساسات
* Get news by sentiment
*
* @param {string} sentiment - 'positive', 'negative', or 'neutral'
* @param {number} limit - تعداد نتایج / Number of results
* @returns {Promise<Array>}
*
* @example
* const client = new CryptoNewsClient();
* const positiveNews = await client.getNewsBySentiment('positive');
* positiveNews.forEach(article => console.log(article.title));
*/
async getNewsBySentiment(sentiment, limit = 50) {
try {
const url = `${this.baseUrl}/api/news?sentiment=${sentiment}&limit=${limit}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
const articles = data.articles || [];
// فیلتر سمت کلاینت / Client-side filter
return articles.filter(a => a.sentiment === sentiment);
} catch (error) {
console.error('Error:', error);
return [];
}
}
/**
* دریافت اخبار از یک منبع خاص
* Get news from a specific source
*
* @param {string} source - نام منبع / Source name
* @param {number} limit - تعداد نتایج / Number of results
* @returns {Promise<Array>}
*
* @example
* const client = new CryptoNewsClient();
* const coinDeskNews = await client.getNewsBySource('CoinDesk');
*/
async getNewsBySource(source, limit = 50) {
try {
const url = `${this.baseUrl}/api/news?source=${encodeURIComponent(source)}&limit=${limit}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
return data.articles || [];
} catch (error) {
console.error('Error:', error);
return [];
}
}
/**
* جستجوی اخبار بر اساس کلمه کلیدی
* Search news by keyword
*
* @param {string} keyword - کلمه کلیدی / Keyword
* @param {number} limit - تعداد نتایج / Number of results
* @returns {Promise<Array>}
*
* @example
* const client = new CryptoNewsClient();
* const bitcoinNews = await client.searchNews('bitcoin');
* console.log(`Found ${bitcoinNews.length} articles about Bitcoin`);
*/
async searchNews(keyword, limit = 100) {
const articles = await this.getAllNews(limit);
const keywordLower = keyword.toLowerCase();
return articles.filter(article => {
const title = (article.title || '').toLowerCase();
const content = (article.content || '').toLowerCase();
return title.includes(keywordLower) || content.includes(keywordLower);
});
}
/**
* دریافت آخرین اخبار
* Get latest news
*
* @param {number} count - تعداد نتایج / Number of results
* @returns {Promise<Array>}
*
* @example
* const client = new CryptoNewsClient();
* const latest = await client.getLatestNews(5);
* latest.forEach(article => {
* console.log(`${article.title} - ${article.published_at}`);
* });
*/
async getLatestNews(count = 10) {
const articles = await this.getAllNews(100);
// مرتبسازی بر اساس تاریخ انتشار / Sort by publish date
const sorted = articles.sort((a, b) => {
const dateA = new Date(a.published_at || 0);
const dateB = new Date(b.published_at || 0);
return dateB - dateA;
});
return sorted.slice(0, count);
}
/**
* دریافت آمار اخبار
* Get news statistics
*
* @returns {Promise<Object>} آمار / Statistics
*
* @example
* const client = new CryptoNewsClient();
* const stats = await client.getNewsStatistics();
* console.log(`Total: ${stats.total}`);
* console.log(`Positive: ${stats.positive}`);
*/
async getNewsStatistics() {
const articles = await this.getAllNews();
const stats = {
total: articles.length,
positive: articles.filter(a => a.sentiment === 'positive').length,
negative: articles.filter(a => a.sentiment === 'negative').length,
neutral: articles.filter(a => a.sentiment === 'neutral').length,
sources: new Set(articles.map(a => a.source?.title || '')).size
};
return stats;
}
}
// ==============================================================================
// مثالهای استفاده / Usage Examples
// ==============================================================================
/**
* مثال ۱: استفاده ساده / Example 1: Basic Usage
*/
async function example1BasicUsage() {
console.log('='.repeat(60));
console.log('مثال ۱: دریافت تمام اخبار / Example 1: Get All News');
console.log('='.repeat(60));
const client = new CryptoNewsClient();
const articles = await client.getAllNews(10);
console.log(`\nتعداد مقالات / Number of articles: ${articles.length}\n`);
articles.slice(0, 5).forEach((article, i) => {
console.log(`${i + 1}. ${article.title || 'No title'}`);
console.log(` منبع / Source: ${article.source?.title || 'Unknown'}`);
console.log(` احساسات / Sentiment: ${article.sentiment || 'neutral'}`);
console.log('');
});
}
/**
* مثال ۲: فیلتر بر اساس احساسات / Example 2: Sentiment Filtering
*/
async function example2SentimentFiltering() {
console.log('='.repeat(60));
console.log('مثال ۲: فیلتر اخبار مثبت / Example 2: Positive News Filter');
console.log('='.repeat(60));
const client = new CryptoNewsClient();
const positiveNews = await client.getNewsBySentiment('positive', 50);
console.log(`\nاخبار مثبت / Positive news: ${positiveNews.length}\n`);
positiveNews.slice(0, 3).forEach(article => {
console.log(`✓ ${article.title || 'No title'}`);
console.log(` ${(article.content || '').substring(0, 100)}...`);
console.log('');
});
}
/**
* مثال ۳: جستجو با کلمه کلیدی / Example 3: Keyword Search
*/
async function example3KeywordSearch() {
console.log('='.repeat(60));
console.log('مثال ۳: جستجوی بیتکوین / Example 3: Bitcoin Search');
console.log('='.repeat(60));
const client = new CryptoNewsClient();
const bitcoinNews = await client.searchNews('bitcoin');
console.log(`\nمقالات مرتبط با بیتکوین / Bitcoin articles: ${bitcoinNews.length}\n`);
bitcoinNews.slice(0, 5).forEach(article => {
console.log(`• ${article.title || 'No title'}`);
});
}
/**
* مثال ۴: آمار اخبار / Example 4: News Statistics
*/
async function example4Statistics() {
console.log('='.repeat(60));
console.log('مثال ۴: آمار اخبار / Example 4: Statistics');
console.log('='.repeat(60));
const client = new CryptoNewsClient();
const stats = await client.getNewsStatistics();
console.log('\n📊 آمار / Statistics:');
console.log(` مجموع مقالات / Total: ${stats.total}`);
console.log(` مثبت / Positive: ${stats.positive} (${(stats.positive/stats.total*100).toFixed(1)}%)`);
console.log(` منفی / Negative: ${stats.negative} (${(stats.negative/stats.total*100).toFixed(1)}%)`);
console.log(` خنثی / Neutral: ${stats.neutral} (${(stats.neutral/stats.total*100).toFixed(1)}%)`);
console.log(` منابع / Sources: ${stats.sources}`);
}
/**
* مثال ۵: آخرین اخبار / Example 5: Latest News
*/
async function example5LatestNews() {
console.log('='.repeat(60));
console.log('مثال ۵: آخرین اخبار / Example 5: Latest News');
console.log('='.repeat(60));
const client = new CryptoNewsClient();
const latest = await client.getLatestNews(5);
console.log('\n🕒 آخرین اخبار / Latest news:\n');
latest.forEach((article, i) => {
const published = article.published_at || '';
const timeStr = published ? new Date(published).toLocaleString() : 'Unknown time';
console.log(`${i + 1}. ${article.title || 'No title'}`);
console.log(` زمان / Time: ${timeStr}`);
console.log('');
});
}
/**
* مثال ۶: فیلتر پیشرفته / Example 6: Advanced Filtering
*/
async function example6AdvancedFiltering() {
console.log('='.repeat(60));
console.log('مثال ۶: فیلتر ترکیبی / Example 6: Combined Filters');
console.log('='.repeat(60));
const client = new CryptoNewsClient();
// دریافت اخبار مثبت درباره اتریوم
// Get positive news about Ethereum
const allNews = await client.getAllNews(100);
const filtered = allNews.filter(article => {
const isPositive = article.sentiment === 'positive';
const isEthereum = (article.title || '').toLowerCase().includes('ethereum');
return isPositive && isEthereum;
});
console.log(`\nاخبار مثبت درباره اتریوم / Positive Ethereum news: ${filtered.length}\n`);
filtered.slice(0, 3).forEach(article => {
console.log(`✓ ${article.title || 'No title'}`);
console.log(` منبع / Source: ${article.source?.title || 'Unknown'}`);
console.log('');
});
}
/**
* تابع اصلی / Main function
*/
async function main() {
console.log('\n' + '='.repeat(60));
console.log('نمونههای استفاده از API اخبار کریپتو');
console.log('Crypto News API Usage Examples');
console.log('='.repeat(60) + '\n');
try {
// اجرای تمام مثالها / Run all examples
await example1BasicUsage();
console.log('\n');
await example2SentimentFiltering();
console.log('\n');
await example3KeywordSearch();
console.log('\n');
await example4Statistics();
console.log('\n');
await example5LatestNews();
console.log('\n');
await example6AdvancedFiltering();
} catch (error) {
console.error('\nخطا / Error:', error.message);
console.error('لطفاً مطمئن شوید که سرور در حال اجرا است');
console.error('Please make sure the server is running');
}
}
// اجرای برنامه اگر به صورت مستقیم فراخوانی شود
// Run the program if executed directly
if (typeof window === 'undefined') {
// Node.js environment
main();
} else {
// Browser environment - export for use
window.CryptoNewsClient = CryptoNewsClient;
console.log('CryptoNewsClient class is now available globally');
console.log('Usage: const client = new CryptoNewsClient();');
}
// Export for ES6 modules
export { CryptoNewsClient };
export default CryptoNewsClient;
|