insomnia/app/common/har.js

62 lines
1.9 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 util from './misc';
import * as misc from './misc';
2016-11-22 22:26:52 +00:00
import {newBodyRaw} from '../models/request';
export function exportHarWithRequest (renderedRequest, addContentLength = false) {
2016-08-15 22:31:30 +00:00
2016-11-22 22:26:52 +00:00
let postData = '';
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-09-24 03:06:38 +00:00
return {
method: renderedRequest.method,
url: util.prepareUrlForSending(renderedRequest.url),
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 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
}));
}