@docuseal/api
Version:
JavaScript / TypeScript library for the DocuSeal API
85 lines (84 loc) • 3.04 kB
JavaScript
import * as https from "node:https";
import * as http from "node:http";
import { URL } from "node:url";
import VERSION from "./version.js";
export class DocusealApiError extends Error {
constructor(message) {
super(message);
this.name = "DocusealApiError";
}
}
export class Http {
constructor(config) {
this.config = config;
}
async get(path, params) {
const url = new 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 URL(this.config.url + path);
return this.request("POST", url, data);
}
async put(path, data) {
const url = new URL(this.config.url + path);
return this.request("PUT", url, data);
}
async delete(path, params) {
const url = new 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}`,
},
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();
});
}
}