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.

62 lines 2.87 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const node_libcurl_1 = require("node-libcurl"); const utils_1 = require("./utils"); const handleQueryString = (curl, url, qs) => { url = qs && Object.keys(qs).length ? (0, utils_1.handleQs)(url, qs) : url; curl.setOpt(node_libcurl_1.Curl.option.URL, url); return url; }; const handleOutgoingHeaders = (curl, returnedHeaderArray) => { curl.setOpt(node_libcurl_1.Curl.option.HEADERFUNCTION, (headerLine) => { returnedHeaderArray.push(headerLine.toString('utf-8').trim()); return headerLine.length; }); }; const handleBody = (curl, options, buffer, httpHeaders) => { if (options.json) { httpHeaders.push('Content-Type: application/json'); curl.setOpt(node_libcurl_1.Curl.option.POSTFIELDS, JSON.stringify(options.json)); } else if (options.body) { curl.setOpt(node_libcurl_1.Curl.option.POSTFIELDS, String(options.body)); } curl.setOpt(node_libcurl_1.Curl.option.WRITEFUNCTION, (buff, nmemb, size) => { buffer.body = Buffer.concat([buffer.body, buff.subarray(0, nmemb * size)]); return nmemb * size; }); }; const request = (method, url, options = {}) => { // Initialing curl object with custom options const curl = new node_libcurl_1.Easy(); curl.setOpt(node_libcurl_1.Curl.option.CUSTOMREQUEST, method); curl.setOpt(node_libcurl_1.Curl.option.TIMEOUT, options.timeout || false); curl.setOpt(node_libcurl_1.Curl.option.FOLLOWLOCATION, options.followRedirects === undefined || options.followRedirects); curl.setOpt(node_libcurl_1.Curl.option.MAXREDIRS, options.maxRedirects || Number.MAX_SAFE_INTEGER); // Query string parameters handleQueryString(curl, url, options.qs); // Headers (both incoming and outgoing) const httpHeaders = (0, utils_1.parseIncomingHeaders)(options.headers); const returnedHeaderArray = []; handleOutgoingHeaders(curl, returnedHeaderArray); // Body (and JSON) const bufferWrap = { body: Buffer.alloc(0) }; handleBody(curl, options, bufferWrap, httpHeaders); // Execute request curl.setOpt(node_libcurl_1.Curl.option.HTTPHEADER, httpHeaders); const code = curl.perform(); (0, utils_1.checkValidCurlCode)(code, method, url, options); // Creating return object const statusCode = curl.getInfo('RESPONSE_CODE').data; const headers = (0, utils_1.parseReturnedHeaders)(returnedHeaderArray); const body = bufferWrap.body; const getBody = (encoding) => { (0, utils_1.checkGetBodyStatus)(statusCode, body); return typeof encoding === 'string' ? body.toString(encoding) : body; }; url = curl.getInfo('EFFECTIVE_URL').data; curl.close(); return { statusCode, headers, body, getBody, url }; }; exports.default = request; //# sourceMappingURL=request.js.map