UNPKG

@docuseal/api

Version:

JavaScript / TypeScript library for the DocuSeal API

90 lines (89 loc) 3.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Http = exports.DocusealApiError = void 0; const https = require("node:https"); const http = require("node:http"); const node_url_1 = require("node:url"); const version_js_1 = require("./version.js"); class DocusealApiError extends Error { constructor(message) { super(message); this.name = "DocusealApiError"; } } exports.DocusealApiError = DocusealApiError; class Http { constructor(config) { this.config = config; } async get(path, params) { const url = new node_url_1.URL(this.config.url + path); if (params) { Object.keys(params).forEach((key) => url.searchParams.append(key, String(params[key]))); } return this.request("GET", url); } async post(path, data) { const url = new node_url_1.URL(this.config.url + path); return this.request("POST", url, data); } async put(path, data) { const url = new node_url_1.URL(this.config.url + path); return this.request("PUT", url, data); } async delete(path, params) { const url = new node_url_1.URL(this.config.url + path); if (params) { Object.keys(params).forEach((key) => url.searchParams.append(key, String(params[key]))); } return this.request("DELETE", url); } request(method, url, data) { return new Promise((resolve, reject) => { const options = { method, hostname: url.hostname, port: url.port || (url.protocol === "https:" ? 443 : 80), path: url.pathname + url.search, headers: { "X-Auth-Token": this.config.key, "Content-Type": "application/json", "User-Agent": `DocuSeal JS v${version_js_1.default}`, }, timeout: this.config.openTimeout, }; const transport = url.protocol === "https:" ? https : http; const req = transport.request(options, (res) => { let body = ""; res.on("data", (chunk) => { body += chunk; }); res.on("end", () => { try { if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) { resolve(body ? JSON.parse(body) : {}); } else { reject(new DocusealApiError(`HTTP Error: ${res.statusCode} - ${body || res.statusMessage || "Unknown error"}`)); } } catch (error) { reject(error); } }); }); req.on("error", (err) => reject(err)); req.on("timeout", () => { req.destroy(new DocusealApiError("Request timeout")); reject(new DocusealApiError("Request timeout")); }); if (data) { req.write(JSON.stringify(data)); } req.end(); }); } } exports.Http = Http;