|
| 1 | +import axios from 'axios'; |
| 2 | +import handleError from './utils/handleError.js'; |
| 3 | +import { ZodType } from 'zod'; |
| 4 | +import { zodToJsonSchema } from 'zod-to-json-schema'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Search and extract information from multiple web sources using AI. |
| 8 | + * |
| 9 | + * @param {string} apiKey - Your ScrapeGraph AI API key |
| 10 | + * @param {string} prompt - Natural language prompt describing what data to extract |
| 11 | + * @param {Object} [schema] - Optional schema object defining the output structure |
| 12 | + * @param {String} userAgent - the user agent like "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" |
| 13 | + * @returns {Promise<string>} Extracted data in JSON format matching the provided schema |
| 14 | + * @throws - Will throw an error in case of an HTTP failure. |
| 15 | + */ |
| 16 | +export async function searchScraper(apiKey, prompt, schema = null, userAgent = null) { |
| 17 | + const endpoint = 'https://api.scrapegraphai.com/v1/searchscraper'; |
| 18 | + const headers = { |
| 19 | + 'accept': 'application/json', |
| 20 | + 'SGAI-APIKEY': apiKey, |
| 21 | + 'Content-Type': 'application/json', |
| 22 | + }; |
| 23 | + |
| 24 | + if (userAgent) headers['User-Agent'] = userAgent; |
| 25 | + |
| 26 | + const payload = { |
| 27 | + user_prompt: prompt, |
| 28 | + }; |
| 29 | + |
| 30 | + if (schema) { |
| 31 | + if (schema instanceof ZodType) { |
| 32 | + payload.output_schema = zodToJsonSchema(schema); |
| 33 | + } else { |
| 34 | + throw new Error('The schema must be an instance of a valid Zod schema'); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + try { |
| 39 | + const response = await axios.post(endpoint, payload, { headers }); |
| 40 | + return response.data; |
| 41 | + } catch (error) { |
| 42 | + handleError(error); |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * Retrieve the status or the result of searchScraper request. It also allows you to see the result of old requests. |
| 48 | + * |
| 49 | + * @param {string} apiKey - Your ScrapeGraph AI API key |
| 50 | + * @param {string} requestId - The request ID associated with the output of a searchScraper request. |
| 51 | + * @returns {Promise<string>} Information related to the status or result of a scraping request. |
| 52 | + */ |
| 53 | +export async function getSearchScraperRequest(apiKey, requestId) { |
| 54 | + const endpoint = 'https://api.scrapegraphai.com/v1/searchscraper/' + requestId; |
| 55 | + const headers = { |
| 56 | + 'accept': 'application/json', |
| 57 | + 'SGAI-APIKEY': apiKey, |
| 58 | + }; |
| 59 | + |
| 60 | + try { |
| 61 | + const response = await axios.get(endpoint, { headers }); |
| 62 | + return response.data; |
| 63 | + } catch (error) { |
| 64 | + handleError(error); |
| 65 | + } |
| 66 | +} |
0 commit comments