(options)
| 113 | }; |
| 114 | |
| 115 | function httpRequest(options) { |
| 116 | let url; |
| 117 | try { |
| 118 | url = parse(options.url); |
| 119 | } catch (e) { |
| 120 | return Promise.reject(e); |
| 121 | } |
| 122 | options = Object.assign(options, encodeBody(options)); |
| 123 | // support params options |
| 124 | if (typeof options.params === 'object') { |
| 125 | options.qs = options.params; |
| 126 | } else if (typeof options.params === 'string') { |
| 127 | options.qs = querystring.parse(options.params); |
| 128 | } |
| 129 | const client = clients[url.protocol]; |
| 130 | if (!client) { |
| 131 | return Promise.reject(`Unsupported protocol ${url.protocol}`); |
| 132 | } |
| 133 | const requestOptions = { |
| 134 | method: options.method, |
| 135 | port: Number(url.port), |
| 136 | path: url.pathname, |
| 137 | hostname: url.hostname, |
| 138 | headers: options.headers, |
| 139 | encoding: null, |
| 140 | followRedirects: options.followRedirects === true, |
| 141 | }; |
| 142 | if (requestOptions.headers) { |
| 143 | Object.keys(requestOptions.headers).forEach(key => { |
| 144 | if (typeof requestOptions.headers[key] === 'undefined') { |
| 145 | delete requestOptions.headers[key]; |
| 146 | } |
| 147 | }); |
| 148 | } |
| 149 | if (url.search) { |
| 150 | options.qs = Object.assign({}, options.qs, querystring.parse(url.query)); |
| 151 | } |
| 152 | if (url.auth) { |
| 153 | requestOptions.auth = url.auth; |
| 154 | } |
| 155 | if (options.qs) { |
| 156 | requestOptions.path += `?${querystring.stringify(options.qs)}`; |
| 157 | } |
| 158 | if (options.agent) { |
| 159 | requestOptions.agent = options.agent; |
| 160 | } |
| 161 | return new Promise((resolve, reject) => { |
| 162 | const req = client.request(requestOptions, makeCallback(resolve, reject, options)); |
| 163 | if (options.body) { |
| 164 | req.write(options.body); |
| 165 | } |
| 166 | req.on('error', error => { |
| 167 | reject(error); |
| 168 | }); |
| 169 | req.end(); |
| 170 | }); |
| 171 | } |
| 172 | module.exports = httpRequest; |
no test coverage detected