UNPKG

node-libcurl

Version:

The fastest http(s) client (and much more) for Node.js - Node.js bindings for libcurl

123 lines 3.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.curly = void 0; /** * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const CurlOption_1 = require("./generated/CurlOption"); const Curl_1 = require("./Curl"); // This is basically http.METHODS const methods = [ 'acl', 'bind', 'checkout', 'connect', 'copy', 'delete', 'get', 'head', 'link', 'lock', 'm-search', 'merge', 'mkactivity', 'mkcalendar', 'mkcol', 'move', 'notify', 'options', 'patch', 'post', 'propfind', 'proppatch', 'purge', 'put', 'rebind', 'report', 'search', 'source', 'subscribe', 'trace', 'unbind', 'unlink', 'unlock', 'unsubscribe', ]; const create = () => { function curly(url, options = {}) { const curlHandle = new Curl_1.Curl(); curlHandle.setOpt('URL', url); for (const key of Object.keys(options)) { const keyTyped = key; const optionName = keyTyped in CurlOption_1.CurlOptionCamelCaseMap ? CurlOption_1.CurlOptionCamelCaseMap[keyTyped] : keyTyped; // @ts-ignore @TODO Try to type this curlHandle.setOpt(optionName, options[key]); } return new Promise((resolve, reject) => { try { curlHandle.on('end', (statusCode, data, headers) => { curlHandle.close(); resolve({ statusCode: statusCode, data: data, headers: headers, }); }); curlHandle.on('error', (error, errorCode) => { curlHandle.close(); // @ts-ignore error.code = errorCode; reject(error); }); curlHandle.perform(); } catch (error) { curlHandle.close(); reject(error); } }); } curly.create = create; const httpMethodOptionsMap = { get: null, post: (_m, o) => ({ post: true, ...o, }), head: (_m, o) => ({ nobody: true, ...o, }), _: (m, o) => ({ customRequest: m, ...o, }), }; for (const httpMethod of methods) { const httpMethodOptionsKey = httpMethodOptionsMap.hasOwnProperty(httpMethod) ? httpMethod : '_'; const httpMethodOptions = httpMethodOptionsMap[httpMethodOptionsKey]; // @ts-ignore curly[httpMethod] = httpMethodOptions === null ? curly : (url, options = {}) => curly(url, { ...httpMethodOptions(httpMethod, options), }); } // @ts-ignore return curly; }; /** * Curly function * * @public */ exports.curly = create(); //# sourceMappingURL=curly.js.map