import axios from 'axios'; import { SolverApiResponse } from './types'; import { SolverTask } from './types/tasks'; import { SolverError } from './errors'; export class Handler { private t: SolverTask; private k: string | undefined; private mp: boolean; constructor({ task, apiKey, mustPoll = true, }: { task: SolverTask; apiKey?: string; mustPoll?: boolean; }) { this.t = task; this.k = apiKey; this.mp = mustPoll; } public async execute(pd: number): Promise { try { if (this.mp) { return await this.poll((await this.create()).taskId!, pd); } else { return (await this.create()).solution; } } catch (err) { throw err; } } private async create(): Promise { try { const res = ( await axios({ method: 'post', url: 'https://api.capsolver.com/createTask', data: { clientKey: this.k, appId: 'FC3D8005-4358-4E90-8835-0B0456FFE2FA', task: this.t, }, }) ).data as SolverApiResponse; // console.log(JSON.stringify(res)); if (res.errorId !== 0) { throw new SolverError('Failed to create task', res); } return res; } catch (err) { if (axios.isAxiosError(err)) { throw new SolverError( 'Failed to create task', err.response?.data || { errorCode: err.message } ); } throw err; } } private async poll(tid: string, pd: number): Promise { let t = 0; while (t <= 50) { const res = ( await axios({ method: 'post', url: 'https://api.capsolver.com/getTaskResult', data: { clientKey: this.k, taskId: tid }, }) ).data as SolverApiResponse; // console.log(JSON.stringify(res)); if (res.errorId !== 0) { throw new SolverError('Failed to retrieve task solution', res); } if (res.status === 'ready') { return res.solution || res; } await new Promise((r) => setTimeout(r, pd)); t++; } throw new SolverError('Failed retrieving task solution. Error threshold excedeed.', { taskId: tid, }); } }