insomnia/app/lib/request.js

55 lines
1.5 KiB
JavaScript
Raw Normal View History

2016-04-09 21:08:55 +00:00
import networkRequest from 'request'
2016-04-10 02:58:48 +00:00
import render from './render'
2016-04-09 21:08:55 +00:00
export default function (request, callback) {
const config = {
url: request.url,
2016-04-10 02:58:48 +00:00
method: request.method,
body: request.body,
headers: {}
2016-04-09 21:08:55 +00:00
};
if (request.authentication.username) {
config.auth = {
user: request.authentication.username,
pass: request.authentication.password
}
}
2016-04-12 06:03:52 +00:00
// TODO: Do these need to be urlencoded or something?
2016-04-10 02:58:48 +00:00
for (let i = 0; i < request.headers.length; i++) {
let header = request.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-12 06:03:52 +00:00
// TODO: this is just a POC. It breaks in a lot of cases
config.url += request.params.map((p, i) => {
const name = encodeURIComponent(p.name);
const value = encodeURIComponent(p.value);
return `${i === 0 ? '?' : '&'}${name}=${value}`;
}).join('');
2016-04-09 21:41:27 +00:00
2016-04-10 02:58:48 +00:00
// SNEAKY HACK: Render nested object by converting it to JSON then rendering
const context = {template_id: 'tem_WWq2w9uJNR6Pqk8APkvsS3'};
const template = JSON.stringify(config);
const renderedConfig = JSON.parse(render(template, context));
networkRequest(renderedConfig, function (err, response) {
if (err) {
return callback(err);
} else {
return callback(null, {
body: response.body,
contentType: response.headers['content-type'],
2016-04-10 06:37:22 +00:00
statusCode: response.statusCode,
headers: Object.keys(response.headers).map(name => {
const value = response.headers[name];
return {name, value};
})
2016-04-10 02:58:48 +00:00
});
}
2016-04-09 21:08:55 +00:00
});
}