const apiKey = process.env.URL2LLM_API_KEY
if (!apiKey) throw new Error('Set URL2LLM_API_KEY before running this example')
export class ApiError extends Error {
constructor(status, result, retryAfter) {
const message = typeof result?.error?.message === 'string' ? result.error.message : 'Request failed'
super(`${status}: ${message}`)
this.status = status
this.code = result?.error?.code
this.requestId = result?.request_id
this.retryAfter = retryAfter
}
}
export async function request(path, { method = 'GET', body, operationKey } = {}) {
const response = await fetch(`https://api.url2llm.com${path}`, {
method,
headers: {
Authorization: `Bearer ${apiKey}`,
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
...(operationKey ? { 'Idempotency-Key': operationKey } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(190_000),
})
let result
try {
result = await response.json()
} catch (error) {
if (response.ok) throw error
throw new ApiError(response.status, {}, response.headers.get('Retry-After'))
}
if (!response.ok || !result?.success) {
throw new ApiError(response.status, result, response.headers.get('Retry-After'))
}
return result
}
export async function* pages(path, limit = 10, cursor) {
do {
const params = new URLSearchParams({ limit: String(limit) })
if (cursor != null) params.set('cursor', String(cursor))
const result = await request(`${path}?${params}`)
yield result.data
cursor = result.data.next_cursor
} while (cursor != null)
}