insomnia/app/lib/network.js

157 lines
4.7 KiB
JavaScript
Raw Normal View History

import networkRequest from 'request';
2016-08-31 20:50:27 +00:00
import {parse as urlParse, format as urlFormat} from 'url';
import * as db from '../database';
import * as querystring from './querystring';
import {DEBOUNCE_MILLIS} from './constants';
2016-07-20 21:15:11 +00:00
import {STATUS_CODE_PEBKAC} from './constants';
2016-07-20 23:16:28 +00:00
import {getRenderedRequest} from './render';
import {jarFromCookies, cookiesFromJar} from './cookies';
2016-04-09 21:08:55 +00:00
2016-08-31 20:50:27 +00:00
function buildRequestConfig (renderedRequest, patch = {}) {
2016-04-09 21:08:55 +00:00
const config = {
2016-08-31 20:50:27 +00:00
method: renderedRequest.method,
body: renderedRequest.body,
2016-04-28 07:30:26 +00:00
headers: {},
// Setup redirect rules
followAllRedirects: true,
maxRedirects: 20,
2016-07-29 00:24:05 +00:00
timeout: 0,
2016-04-28 07:30:26 +00:00
// Unzip gzipped responses
gzip: true,
// Time the request
time: true,
// SSL Checking
rejectUnauthorized: true,
// Proxy
proxy: null
2016-04-09 21:08:55 +00:00
};
// Set the URL, including the query parameters
2016-08-31 20:50:27 +00:00
const qs = querystring.buildFromParams(renderedRequest.parameters);
2016-08-31 20:52:48 +00:00
const url = querystring.joinURL(renderedRequest.url, qs);
2016-07-15 03:50:59 +00:00
2016-08-31 20:50:27 +00:00
// Encode path portion of URL
const parsedUrl = urlParse(url);
parsedUrl.pathname = encodeURI(parsedUrl.pathname);
config.url = urlFormat(parsedUrl);
for (let i = 0; i < renderedRequest.headers.length; i++) {
let header = renderedRequest.headers[i];
2016-04-12 00:39:49 +00:00
if (header.name) {
config.headers[header.name] = header.value;
}
2016-04-09 21:08:55 +00:00
}
2016-04-28 07:30:26 +00:00
return Object.assign(config, patch);
}
function actuallySend (renderedRequest, settings) {
2016-07-20 21:15:11 +00:00
return new Promise((resolve, reject) => {
const cookieJar = renderedRequest.cookieJar;
const jar = jarFromCookies(cookieJar.cookies);
// Detect and set the proxy based on the request protocol
// NOTE: request does not have a separate settings for http/https proxies
const {protocol} = urlParse(renderedRequest.url);
const proxyHost = protocol === 'https:' ? settings.httpsProxy : settings.httpProxy;
const proxy = proxyHost ? `${protocol}//${proxyHost}` : null;
let config = buildRequestConfig(renderedRequest, {
jar: jar,
proxy: proxy,
followAllRedirects: settings.followRedirects,
timeout: settings.timeout > 0 ? settings.timeout : null,
rejectUnauthorized: settings.validateSSL
2016-07-20 21:15:11 +00:00
}, true);
const startTime = Date.now();
// TODO: Handle redirects ourselves
networkRequest(config, function (err, networkResponse) {
2016-07-20 21:15:11 +00:00
if (err) {
db.responseCreate({
parentId: renderedRequest._id,
elapsedTime: Date.now() - startTime,
2016-07-20 21:15:11 +00:00
error: err.toString()
});
return reject(err);
}
// TODO: Add image support to Insomnia
const contentType = networkResponse.headers['content-type'];
if (contentType && contentType.toLowerCase().indexOf('image/') === 0) {
const err = new Error(`Content-Type ${contentType} not supported`);
db.responseCreate({
parentId: renderedRequest._id,
elapsedTime: Date.now() - startTime,
error: err.toString(),
statusMessage: 'UNSUPPORTED'
});
return reject(err);
}
// Update the cookie jar
cookiesFromJar(jar).then(cookies => {
db.cookieJarUpdate(cookieJar, {cookies});
});
// Format the headers into Insomnia format
// TODO: Move this to a better place
const headers = [];
for (const name of Object.keys(networkResponse.headers)) {
const tmp = networkResponse.headers[name];
const values = Array.isArray(tmp) ? tmp : [tmp];
for (const value of values) {
headers.push({name, value});
}
}
2016-07-20 21:15:11 +00:00
const responsePatch = {
parentId: renderedRequest._id,
statusCode: networkResponse.statusCode,
statusMessage: networkResponse.statusMessage,
contentType: networkResponse.headers['content-type'],
url: config.url, // TODO: Handle redirects somehow
elapsedTime: networkResponse.elapsedTime,
bytesRead: networkResponse.connection.bytesRead,
body: networkResponse.body,
headers: headers
2016-07-20 21:15:11 +00:00
};
2016-04-28 07:30:26 +00:00
2016-07-20 21:15:11 +00:00
db.responseCreate(responsePatch).then(resolve, reject);
})
})
2016-04-09 21:08:55 +00:00
}
2016-07-20 21:15:11 +00:00
export function send (requestId) {
return new Promise((resolve, reject) => {
// First, lets wait for all debounces to finish
setTimeout(() => {
Promise.all([
db.requestGetById(requestId),
db.settingsGetOrCreate()
]).then(([request, settings]) => {
getRenderedRequest(request).then(renderedRequest => {
actuallySend(renderedRequest, settings).then(resolve, reject);
}, err => {
db.responseCreate({
parentId: request._id,
statusCode: STATUS_CODE_PEBKAC,
error: err.message
}).then(resolve, reject);
});
})
}, DEBOUNCE_MILLIS);
}
)
}