UNPKG

@davidbolaji/termii-node

Version:

Node.js SDK for Termii API – send SMS, voice, OTP, and manage messaging with ease.

57 lines (56 loc) 2.16 kB
import axios from "axios"; import { HttpError } from "../types"; import FormData from "form-data"; export class HttpClient { constructor(options) { var _a; this.apiKey = options.apiKey; this.client = axios.create({ baseURL: (_a = options.baseURL) !== null && _a !== void 0 ? _a : "https://api.ng.termii.com/api", }); } async request(path, options = {}) { var _a, _b, _c; try { const isFormData = options.data instanceof FormData; let params = options.params || {}; let data = options.data || undefined; let headers = { ...(options.headers || {}), ...(isFormData || options.raw ? {} : { Accept: "application/json", "Content-Type": "application/json" }), }; // ✅ Decide where to inject api_key switch (options.authLocation) { case "query": params = { ...params, api_key: this.apiKey }; break; case "body": if (!isFormData) { data = { ...(data || {}), api_key: this.apiKey }; } break; case "none": headers["X-Token"] = this.apiKey; // 🔑 attach as header break; default: break; } const response = await this.client.request({ url: path, method: options.method || "GET", data, params, headers, }); return response.data; } catch (error) { const err = error; const payload = ((_a = err.response) === null || _a === void 0 ? void 0 : _a.data) || { code: (_b = err.response) === null || _b === void 0 ? void 0 : _b.status, message: err.message }; throw new HttpError(`HTTP Error: ${((_c = err.response) === null || _c === void 0 ? void 0 : _c.status) || "Unknown"}`, payload); } } }