mirror of
https://github.com/MadsLorentzen/ai-job-search.git
synced 2026-09-17 00:26:26 +00:00
68 lines
2.2 KiB
TypeScript
68 lines
2.2 KiB
TypeScript
export const BASE_URL = "https://jobdanmark.dk"
|
|||
|
|
|
||
|
|
export async function apiFetch<T>(path: string, params?: Record<string, string>): Promise<T> {
|
||
|
|
let url = `${BASE_URL}${path}`
|
||
|
|
if (params && Object.keys(params).length > 0) {
|
||
|
|
const qs = new URLSearchParams(params)
|
||
|
|
url += `?${qs.toString()}`
|
||
|
|
}
|
||
|
|
|
||
|
|
const maxRetries = 6
|
||
|
|
let delay = 500
|
||
|
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||
|
|
const response = await fetch(url)
|
||
|
|
if (response.status === 429 || response.status >= 500) {
|
||
|
|
if (attempt === maxRetries) {
|
||
|
|
throw new Error(`API request failed: ${response.status} ${response.statusText}`)
|
||
|
|
}
|
||
|
|
const jitter = Math.floor(Math.random() * 500)
|
||
|
|
await new Promise((resolve) => setTimeout(resolve, delay + jitter))
|
||
|
|
delay = Math.min(delay * 2, 5000)
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
if (!response.ok) {
|
||
|
|
throw new Error(`API request failed: ${response.status} ${response.statusText}`)
|
||
|
|
}
|
||
|
|
return response.json() as Promise<T>
|
||
|
|
}
|
||
|
|
throw new Error("API request failed after max retries")
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function apiPost<T>(path: string, body: unknown): Promise<T> {
|
||
|
|
const url = `${BASE_URL}${path}`
|
||
|
|
|
||
|
|
const maxRetries = 6
|
||
|
|
let delay = 500
|
||
|
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||
|
|
const response = await fetch(url, {
|
||
|
|
method: "POST",
|
||
|
|
headers: {
|
||
|
|
"Content-Type": "application/json",
|
||
|
|
},
|
||
|
|
body: JSON.stringify(body),
|
||
|
|
})
|
||
|
|
if (response.status === 429 || response.status >= 500) {
|
||
|
|
if (attempt === maxRetries) {
|
||
|
|
throw new Error(`API request failed: ${response.status} ${response.statusText}`)
|
||
|
|
}
|
||
|
|
const jitter = Math.floor(Math.random() * 500)
|
||
|
|
await new Promise((resolve) => setTimeout(resolve, delay + jitter))
|
||
|
|
delay = Math.min(delay * 2, 5000)
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
if (!response.ok) {
|
||
|
|
throw new Error(`API request failed: ${response.status} ${response.statusText}`)
|
||
|
|
}
|
||
|
|
return response.json() as Promise<T>
|
||
|
|
}
|
||
|
|
throw new Error("API request failed after max retries")
|
||
|
|
}
|
||
|
|
|
||
|
|
export function writeError(error: string, code: string): void {
|
||
|
|
process.stderr.write(JSON.stringify({ error, code }) + "\n")
|
||
|
|
}
|
||
|
|
|
||
|
|
export function stripHtml(html: string): string {
|
||
|
|
return html.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim()
|
||
|
|
}
|