2016-07-16 02:06:10 +00:00
|
|
|
import nunjucks from 'nunjucks';
|
2016-07-20 23:16:28 +00:00
|
|
|
import * as db from '../database'
|
2016-04-15 02:13:49 +00:00
|
|
|
|
2016-07-20 21:15:11 +00:00
|
|
|
nunjucks.configure({
|
|
|
|
autoescape: false
|
|
|
|
});
|
2016-04-10 02:58:48 +00:00
|
|
|
|
2016-07-20 23:16:28 +00:00
|
|
|
export function render (template, context = {}) {
|
2016-07-20 21:15:11 +00:00
|
|
|
try {
|
|
|
|
return nunjucks.renderString(template, context);
|
|
|
|
} catch (e) {
|
|
|
|
throw new Error(
|
|
|
|
e.message.replace('(unknown path)\n ', '')
|
|
|
|
);
|
|
|
|
}
|
2016-04-10 02:58:48 +00:00
|
|
|
}
|
2016-07-20 23:16:28 +00:00
|
|
|
|
|
|
|
export function getRenderedRequest (request) {
|
2016-08-04 04:12:45 +00:00
|
|
|
return db.requestGetAncestors(request).then(ancestors => {
|
|
|
|
const renderContext = {};
|
|
|
|
|
|
|
|
for (let doc of ancestors) {
|
|
|
|
// TODO: Add support for Workspace environments
|
|
|
|
const environment = doc.environment || {};
|
|
|
|
Object.assign(renderContext, environment);
|
|
|
|
}
|
|
|
|
|
|
|
|
let template;
|
|
|
|
|
|
|
|
try {
|
|
|
|
template = JSON.stringify(request);
|
|
|
|
} catch (e) {
|
|
|
|
// Failed to parse Request as JSON
|
|
|
|
throw new Error(`Bad Request: "${e.message}"`);
|
|
|
|
}
|
|
|
|
|
|
|
|
let renderedJSON;
|
|
|
|
try {
|
|
|
|
renderedJSON = render(template, renderContext);
|
|
|
|
} catch (e) {
|
|
|
|
// Failed to render Request
|
|
|
|
throw new Error(`Render Failed: "${e.message}"`);
|
|
|
|
}
|
|
|
|
|
2016-07-20 23:16:28 +00:00
|
|
|
let renderedRequest = null;
|
2016-08-04 04:12:45 +00:00
|
|
|
try {
|
|
|
|
renderedRequest = JSON.parse(renderedJSON);
|
|
|
|
} catch (e) {
|
|
|
|
// Failed to parse rendered request
|
|
|
|
throw new Error(`Parse Failed: "${e.message}"`);
|
|
|
|
}
|
2016-07-20 23:16:28 +00:00
|
|
|
|
2016-08-04 04:12:45 +00:00
|
|
|
// Default the proto if it doesn't exist
|
|
|
|
if (renderedRequest.url.indexOf('://') === -1) {
|
|
|
|
renderedRequest.url = `http://${renderedRequest.url}`;
|
2016-07-20 23:16:28 +00:00
|
|
|
}
|
2016-08-04 04:12:45 +00:00
|
|
|
|
|
|
|
return new Promise(resolve => resolve(renderedRequest));
|
2016-07-20 23:16:28 +00:00
|
|
|
});
|
|
|
|
}
|