59 lines
2.1 KiB
JavaScript
59 lines
2.1 KiB
JavaScript
// digikala.js
|
|
|
|
async function searchDigikala(query, limit = 12) {
|
|
if (!query?.trim()) return [];
|
|
|
|
const url = `https://api.digikala.com/v3/search/?q=${encodeURIComponent(query.trim())}`;
|
|
|
|
const headers = {
|
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
|
|
'Accept': 'application/json',
|
|
'Accept-Language': 'fa,en;q=0.9',
|
|
'Referer': 'https://www.digikala.com/',
|
|
'Origin': 'https://www.digikala.com',
|
|
'Sec-Fetch-Site': 'same-site',
|
|
'Sec-Fetch-Mode': 'cors',
|
|
'x-api-client': 'web'
|
|
};
|
|
|
|
try {
|
|
const res = await fetch(url, { headers, timeout: 10000 });
|
|
|
|
if (!res.ok) {
|
|
console.error(`❌ API Error: ${res.status} ${res.statusText}`);
|
|
return [];
|
|
}
|
|
|
|
const data = await res.json();
|
|
|
|
// Navigate to product list
|
|
const widgets = data?.data?.widgets?.[0];
|
|
if (!widgets || widgets.type !== 'vertical_product_listing') {
|
|
console.warn('⚠️ Unexpected widget structure');
|
|
return [];
|
|
}
|
|
|
|
const productWidgets = widgets.data?.widgets || [];
|
|
const products = productWidgets
|
|
.filter(w => w.type === 'product')
|
|
.map(w => w.data)
|
|
.slice(0, limit)
|
|
.map(p => ({
|
|
id: p.id,
|
|
title: p.title_fa || 'بدون عنوان',
|
|
image: p.images?.main?.url?.[0] || 'https://dkstatics-public.digikala.com/digikala-products/default.jpg?x-oss-process=image/resize,m_lfit,h_150,w_150',
|
|
rrpPrice: p.default_variant?.price?.sellingPrice || null,
|
|
sellingPrice: p.default_variant?.price?.selling_price || null,
|
|
discountPercent: p.default_variant?.price?.discount_percent || 0,
|
|
link: 'https://www.digikala.com' + (p.url?.uri || `/product/dkp-${p.id}/`)
|
|
}));
|
|
|
|
return products;
|
|
|
|
} catch (err) {
|
|
console.error('🔴 Fetch error:', err.message);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
module.exports = { searchDigikala }; |