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.

60 lines 2.64 kB
import { Curl, Easy } from 'node-libcurl'; import { checkGetBodyStatus, checkValidCurlCode, handleQs, parseReturnedHeaders, parseIncomingHeaders } from './utils'; const handleQueryString = (curl, url, qs) => { url = qs && Object.keys(qs).length ? handleQs(url, qs) : url; curl.setOpt(Curl.option.URL, url); return url; }; const handleOutgoingHeaders = (curl, returnedHeaderArray) => { curl.setOpt(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(Curl.option.POSTFIELDS, JSON.stringify(options.json)); } else if (options.body) { curl.setOpt(Curl.option.POSTFIELDS, String(options.body)); } curl.setOpt(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 Easy(); curl.setOpt(Curl.option.CUSTOMREQUEST, method); curl.setOpt(Curl.option.TIMEOUT, options.timeout || false); curl.setOpt(Curl.option.FOLLOWLOCATION, options.followRedirects === undefined || options.followRedirects); curl.setOpt(Curl.option.MAXREDIRS, options.maxRedirects || Number.MAX_SAFE_INTEGER); // Query string parameters handleQueryString(curl, url, options.qs); // Headers (both incoming and outgoing) const httpHeaders = 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(Curl.option.HTTPHEADER, httpHeaders); const code = curl.perform(); checkValidCurlCode(code, method, url, options); // Creating return object const statusCode = curl.getInfo('RESPONSE_CODE').data; const headers = parseReturnedHeaders(returnedHeaderArray); const body = bufferWrap.body; const getBody = (encoding) => { 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 }; }; export default request; //# sourceMappingURL=request.js.map