UNPKG

sync-request-curl

Version:

Fast way to send synchronous web requests in NodeJS. API is a subset of sync-request. Leverages node-libcurl for high performance. Cannot be used in a browser.

70 lines (67 loc) 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkGetBodyStatus = exports.checkValidCurlCode = exports.parseReturnedHeaders = exports.parseIncomingHeaders = exports.handleQs = void 0; const node_libcurl_1 = require("node-libcurl"); const handleQs = (url, qs) => { const urlObj = new URL(url); Object.entries(qs).forEach(([key, value]) => { if (Array.isArray(value)) { urlObj.searchParams.delete(key); value.forEach((item, i) => urlObj.searchParams.append(`${key}[${i}]`, String(item))); } else if (value === null) { urlObj.searchParams.set(key, ''); } else if (value !== undefined) { urlObj.searchParams.set(key, String(value)); } }); urlObj.search = urlObj.searchParams.toString(); return urlObj.href; }; exports.handleQs = handleQs; const parseIncomingHeaders = (headers) => { return headers ? Object.entries(headers) .filter(([_, value]) => value !== undefined) .map(([key, value]) => value === '' ? `${key};` : `${key}: ${value}`) : []; }; exports.parseIncomingHeaders = parseIncomingHeaders; const parseReturnedHeaders = (headerLines) => { return headerLines.reduce((acc, header) => { const [name, ...values] = header.split(':'); if (name && values.length > 0) { acc[name.trim()] = values.join(':').trim(); } return acc; }, {}); }; exports.parseReturnedHeaders = parseReturnedHeaders; const checkValidCurlCode = (code, method, url, options) => { if (code !== node_libcurl_1.CurlCode.CURLE_OK) { throw new Error(` Curl request failed with code ${code} Please look up libcurl error code! - https://curl.se/libcurl/c/libcurl-errors.html DEBUG: { method: "${method}", url: "${url}", options: ${JSON.stringify(options)} } `); } }; exports.checkValidCurlCode = checkValidCurlCode; const checkGetBodyStatus = (statusCode, body) => { if (statusCode >= 300) { throw new Error(` Server responded with status code ${statusCode} Body: ${body.toString()} Use 'res.body' instead of 'res.getBody()' to not have any errors thrown. The status code (in this case, ${statusCode}) can be checked manually with res.statusCode. `); } }; exports.checkGetBodyStatus = checkGetBodyStatus; //# sourceMappingURL=utils.js.map