insomnia/app/common/har.js

75 lines
2.4 KiB
JavaScript
Raw Normal View History

2016-11-22 22:26:52 +00:00
import fs from 'fs';
2016-11-10 01:15:27 +00:00
import * as models from '../models';
import {getRenderedRequest} from './render';
import {jarFromCookies} from './cookies';
import * as misc from './misc';
2016-11-22 22:26:52 +00:00
import {newBodyRaw} from '../models/request';
import {getAuthHeader} from '../network/authentication';
export async function exportHarWithRequest (renderedRequest, addContentLength = false) {
2016-11-22 22:26:52 +00:00
let postData = '';
const url = misc.prepareUrlForSending(renderedRequest.url, renderedRequest.settingEncodeUrl);
2016-11-22 22:26:52 +00:00
if (renderedRequest.body.fileName) {
try {
postData = newBodyRaw(fs.readFileSync(renderedRequest.body.fileName, 'base64'));
} catch (e) {
console.warn('[code gen] Failed to read file', e);
}
} else {
// For every other type, Insomnia uses the same body format as HAR
postData = renderedRequest.body;
}
2016-11-23 20:44:46 +00:00
if (addContentLength) {
const hasContentLengthHeader = misc.filterHeaders(
renderedRequest.headers,
'content-length'
).length > 0;
if (!hasContentLengthHeader) {
const name = 'content-length';
const value = Buffer.byteLength((renderedRequest.body || {}).text || '').toString();
renderedRequest.headers.push({name, value});
2016-11-23 20:44:46 +00:00
}
}
// Set auth header if we have it
if (!misc.hasAuthHeader(renderedRequest.headers)) {
const header = await getAuthHeader(
renderedRequest._id,
url,
renderedRequest.method,
renderedRequest.authentication
);
header && renderedRequest.headers.push(header);
}
2016-09-24 03:06:38 +00:00
return {
method: renderedRequest.method,
url,
2016-09-24 03:06:38 +00:00
httpVersion: 'HTTP/1.1',
cookies: getCookies(renderedRequest),
headers: renderedRequest.headers,
queryString: renderedRequest.parameters,
postData: postData,
2016-09-24 03:06:38 +00:00
headersSize: -1,
bodySize: -1
};
}
2016-08-15 22:31:30 +00:00
2016-11-17 18:45:54 +00:00
export async function exportHar (requestId, environmentId, addContentLength = false) {
2016-11-10 01:15:27 +00:00
const request = await models.request.getById(requestId);
2016-11-17 18:45:54 +00:00
const renderedRequest = await getRenderedRequest(request, environmentId);
return await exportHarWithRequest(renderedRequest, addContentLength);
}
function getCookies (renderedRequest) {
const jar = jarFromCookies(renderedRequest.cookieJar.cookies);
2016-10-05 15:07:49 +00:00
const domainCookies = jar.getCookiesSync(renderedRequest.url);
2016-10-05 16:34:13 +00:00
return domainCookies.map(c => Object.assign(c.toJSON(), {
name: c.key,
value: c.value || '' // Sometimes cookies don't have values for some reason
}));
}