UNPKG

myinvois-sdk

Version:

TypeScript SDK for interacting with the Malaysia e-invoicing system (MyInvois) API

100 lines (99 loc) 3.2 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MyInvoisApiError = exports.HttpClient = void 0; const axios_1 = __importDefault(require("axios")); /** * HTTP client wrapper around Axios */ class HttpClient { constructor() { this.client = axios_1.default.create({ timeout: 30000, // 30 seconds headers: { 'Content-Type': 'application/json' } }); } /** * Make a GET request * @param url The URL to make the request to * @param config The Axios request configuration * @returns A promise resolving to the response data */ async get(url, config) { try { const response = await this.client.get(url, config); return response.data; } catch (error) { this.handleError(error); } } /** * Make a POST request * @param url The URL to make the request to * @param data The data to send * @param config The Axios request configuration * @returns A promise resolving to the response data */ async post(url, data, config) { try { const response = await this.client.post(url, data, config); return response.data; } catch (error) { this.handleError(error); } } /** * Make a PUT request * @param url The URL to make the request to * @param data The data to send * @param config The Axios request configuration * @returns A promise resolving to the response data */ async put(url, data, config) { try { const response = await this.client.put(url, data, config); return response.data; } catch (error) { this.handleError(error); } } /** * Handle errors from Axios * @param error The error to handle */ handleError(error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx throw new MyInvoisApiError(error.response.data?.message || error.response.statusText, error.response.status, error.response.data); } else if (error.request) { // The request was made but no response was received throw new MyInvoisApiError('No response received from server', 0, { request: error.request }); } else { // Something happened in setting up the request that triggered an Error throw new MyInvoisApiError(error.message || 'Unknown error', 0, {}); } } } exports.HttpClient = HttpClient; /** * Custom error class for API errors */ class MyInvoisApiError extends Error { constructor(message, statusCode, responseData) { super(message); this.name = 'MyInvoisApiError'; this.statusCode = statusCode; this.responseData = responseData; } } exports.MyInvoisApiError = MyInvoisApiError;