Here's a complete Node.js example showing how to loop through all categories and their products:
Complete Example (loop-products.js):
const https = require('https');
const http = require('http');
const API_BASE_URL = '__DYNAMIC_HOST__/api';
const httpsAgent = new https.Agent({
keepAlive: true,
keepAliveMsecs: 30000,
maxSockets: 5,
maxFreeSockets: 2,
timeout: 30000,
freeSocketTimeout: 30000
});
const httpAgent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 30000,
maxSockets: 5,
maxFreeSockets: 2,
timeout: 30000,
freeSocketTimeout: 30000
});
function getAgent(url) {
return url.startsWith('https:') ? httpsAgent : httpAgent;
}
async function fetchWithAgent(url, options = {}) {
return fetch(url, {
...options,
agent: getAgent(url)
});
}
async function processInBatches(items, batchSize, processor) {
const results = [];
for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, i + batchSize);
console.log(`š Processing batch ${Math.floor(i/batchSize) + 1}/${Math.ceil(items.length/batchSize)} (${batch.length} items)`);
const batchResults = await Promise.all(batch.map(processor));
results.push(...batchResults);
if (i + batchSize < items.length) {
await new Promise(resolve => setTimeout(resolve, 250));
}
}
return results;
}
async function getAllCategoriesAndProducts() {
try {
console.log('š Fetching categories...');
const categoriesResponse = await fetchWithAgent(`${API_BASE_URL}/categories`);
const categoriesData = await categoriesResponse.json();
if (!categoriesData.success) throw new Error('Failed to fetch categories');
console.log(`š Found ${categoriesData.categories.length} categories`);
const results = await processInBatches(
categoriesData.categories,
3,
async (category) => {
console.log(`š ${category.name} (ID: ${category.id})`);
try {
const productsResponse = await fetchWithAgent(`${API_BASE_URL}/categories/${category.id}/products`);
const productsData = await productsResponse.json();
if (productsData.success && productsData.products.length > 0) {
console.log(` š¦ ${productsData.products.length} products:`);
const productsWithDetails = await processInBatches(
productsData.products,
5,
async (product) => {
try {
const details = await fetchWithAgent(`${API_BASE_URL}/products/${product.id}`);
const detailsData = await details.json();
return {
product,
details: detailsData.success ? detailsData.product : null
};
} catch (error) {
console.error(` ā Error fetching details for ${product.name}: ${error.message}`);
return { product, details: null };
}
}
);
productsWithDetails.forEach(({ product, details }) => {
console.log(` - ${product.name} (ID: ${product.id})`);
if (details) {
console.log(` ā¬${details.price}`);
}
});
return { category, products: productsWithDetails };
} else {
console.log(' š¦ No products found');
return { category, products: [] };
}
} catch (error) {
console.error(` ā Error fetching products for ${category.name}: ${error.message}`);
return { category, products: [] };
}
}
);
console.log('\nā
Finished');
console.log(`š Processed ${results.length} categories with ${results.reduce((sum, r) => sum + r.products.length, 0)} total products`);
httpsAgent.destroy();
httpAgent.destroy();
return results;
} catch (error) {
console.error('ā Error:', error.message);
httpsAgent.destroy();
httpAgent.destroy();
}
}
getAllCategoriesAndProducts();
Simple Version (basic-loop.js):
const fetch = require('node-fetch');
async function simpleLoop() {
const categories = await fetch('__DYNAMIC_HOST__/api/categories').then(r => r.json());
for (const category of categories.categories) {
console.log(`Category: ${category.name}`);
const products = await fetch(`__DYNAMIC_HOST__/api/categories/${category.id}/products`)
.then(r => r.json());
if (products.success) {
products.products.forEach(p => console.log(` - ${p.name}`));
}
}
}
simpleLoop();
With Authentication (for orders):
const fetch = require('node-fetch');
const API_KEY = 'your-api-key-here';
async function getOrdersExample() {
try {
const response = await fetch('__DYNAMIC_HOST__/api/orders', {
headers: { 'X-API-Key': API_KEY }
});
const data = await response.json();
if (data.success) {
console.log('Orders:', data.orders);
} else {
console.error('Error:', data.error);
}
} catch (error) {
console.error('Request failed:', error.message);
}
}
getOrdersExample();