UNPKG

@cabin-interactive/qrz-api-client

Version:
67 lines (66 loc) 3.26 kB
import { BaseQrzService } from "./base"; import { QrzNetworkError, QrzAuthError, QrzUnknownActionError, QrzQsoValidationError, QrzDuplicateQsoError, QrzQsoStationCallsignError, QrzError } from "../errors"; import { parseQrzResponse } from "../parser"; // STATUS=FAIL&RESULT=FAIL&REASON=Unable to add QSO to database: duplicate&EXTENDED= // STATUS=FAIL&RESULT=FAIL&REASON=wrong station_callsign for this logbook KB0ICTS doesnt match book callsign KB0ICT&EXTENDED= // COUNT=1&LOGID=1193542649&RESULT=OK // STATUS=FAIL&RESULT=FAIL&REASON=Replace error on record: DXCC could not be determined for TEST2&EXTENDED= // COUNT=1&RESULT=REPLACE&LOGID=1193504315 export const QRZ_ERROR_RESPONSES = { DUPLICATE_QSO: 'Unable to add QSO to database: duplicate', WRONG_STATION_CALLSIGN: 'wrong station_callsign for this logbook' }; export class HttpService extends BaseQrzService { async post(params) { var _a, _b, _c, _d, _e; const formData = this.createFormData(params); let rawResponse; try { rawResponse = await this.makeRequest(formData); } catch (error) { if (error instanceof Error) { throw new QrzNetworkError('Failed to connect to QRZ API', undefined, error); } throw error; } const response = parseQrzResponse(rawResponse); // Handle various error responses from the API if (response.status === 'AUTH' || response.result === 'AUTH') { throw new QrzAuthError(response.reason || 'Authentication failed'); } if (response.result === 'FAIL') { if ((_a = response.reason) === null || _a === void 0 ? void 0 : _a.includes(QRZ_ERROR_RESPONSES.DUPLICATE_QSO)) { throw new QrzDuplicateQsoError(response.reason); } if ((_b = response.reason) === null || _b === void 0 ? void 0 : _b.includes(QRZ_ERROR_RESPONSES.WRONG_STATION_CALLSIGN)) { throw new QrzQsoStationCallsignError(response.reason); } if ((_c = response.reason) === null || _c === void 0 ? void 0 : _c.includes('unrecognized command')) { throw new QrzUnknownActionError(response.reason, params.action); } if ((_d = response.reason) === null || _d === void 0 ? void 0 : _d.includes('missing required field')) { const field = (_e = response.reason.match(/field:\s*(\w+)/)) === null || _e === void 0 ? void 0 : _e[1]; throw new QrzQsoValidationError(response.reason, field); } // Generic failure throw new QrzError(response.reason || 'Operation failed'); } return response; } async makeRequest(formData) { const response = await fetch(this.baseUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': this.config.userAgent, }, body: formData.toString(), }); // Handle non-200 HTTP responses if (!response.ok) { throw new QrzNetworkError(`HTTP error! status: ${response.status}`, response.status); } return response.text(); } }