|
| 1 | +import axios from 'axios'; |
| 2 | +import handleError from './utils/handleError.js'; |
| 3 | +import { isMockEnabled, getMockConfig } from './utils/mockConfig.js'; |
| 4 | +import { getMockResponse } from './utils/mockResponse.js'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Converts data to toon format. |
| 8 | + * |
| 9 | + * @param {string} apiKey - Your ScrapeGraph AI API key. |
| 10 | + * @param {Object} data - The data object to be converted to toon format. |
| 11 | + * @param {Object} options - Optional configuration options. |
| 12 | + * @param {boolean} options.mock - Override mock mode for this request |
| 13 | + * @returns {Promise<Object>} A promise that resolves to the toonified data response. |
| 14 | + * @throws {Error} Throws an error if the HTTP request fails. |
| 15 | + * |
| 16 | + * @example |
| 17 | + * // Example usage: |
| 18 | + * const apiKey = 'your-api-key'; |
| 19 | + * const data = { |
| 20 | + * products: [ |
| 21 | + * { sku: "LAP-001", name: "Gaming Laptop", price: 1299.99 }, |
| 22 | + * { sku: "MOU-042", name: "Wireless Mouse", price: 29.99 } |
| 23 | + * ] |
| 24 | + * }; |
| 25 | + * |
| 26 | + * try { |
| 27 | + * const result = await toonify(apiKey, data); |
| 28 | + * console.log('Toonified result:', result); |
| 29 | + * } catch (error) { |
| 30 | + * console.error('Error toonifying data:', error); |
| 31 | + * } |
| 32 | + */ |
| 33 | +export async function toonify(apiKey, data, options = {}) { |
| 34 | + const { mock = null } = options; |
| 35 | + |
| 36 | + // Check if mock mode is enabled |
| 37 | + const useMock = mock !== null ? mock : isMockEnabled(); |
| 38 | + |
| 39 | + if (useMock) { |
| 40 | + console.log('🧪 Mock mode active. Returning stub for toonify request'); |
| 41 | + const mockConfig = getMockConfig(); |
| 42 | + const mockData = getMockResponse('POST', 'https://api.scrapegraphai.com/v1/toonify', mockConfig.customResponses, mockConfig.customHandler); |
| 43 | + return mockData; |
| 44 | + } |
| 45 | + |
| 46 | + const endpoint = 'https://api.scrapegraphai.com/v1/toonify'; |
| 47 | + const headers = { |
| 48 | + 'accept': 'application/json', |
| 49 | + 'SGAI-APIKEY': apiKey, |
| 50 | + 'Content-Type': 'application/json', |
| 51 | + }; |
| 52 | + |
| 53 | + try { |
| 54 | + const response = await axios.post(endpoint, data, { headers }); |
| 55 | + return response.data; |
| 56 | + } catch (error) { |
| 57 | + handleError(error); |
| 58 | + } |
| 59 | +} |
0 commit comments