UNPKG

tggl-client

Version:

Tggl Typescript SDK for client and server

67 lines (66 loc) 2.36 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.apiCall = void 0; var http_1 = __importDefault(require("http")); var https_1 = __importDefault(require("https")); var apiCall = function (_a) { var apiKey = _a.apiKey, body = _a.body, url = _a.url, method = _a.method; var httpModule = url.startsWith('https') ? https_1.default : http_1.default; return new Promise(function (resolve, reject) { var postData = body ? JSON.stringify(body) : ''; var timer = undefined; var req = httpModule.request(url, { method: method, headers: body && apiKey ? { 'x-tggl-api-key': apiKey, 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData), } : body ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData), } : apiKey ? { 'x-tggl-api-key': apiKey, } : {}, }, function (res) { var data = ''; res.on('data', function (chunk) { return (data += chunk); }); res.on('end', function () { clearTimeout(timer); try { if (res.statusCode !== 200) { reject(JSON.parse(data)); } else { resolve(JSON.parse(data)); } } catch (error) { if (error instanceof SyntaxError) { reject(data); } reject(error); } }); }); req.on('error', reject); if (body) { req.write(postData); } req.end(); // @ts-ignore timer = setTimeout(function () { req.destroy(); reject({ error: 'Request timed out' }); }, 10000); }); }; exports.apiCall = apiCall;