insomnia/app/lib/render.js

52 lines
1.2 KiB
JavaScript
Raw Normal View History

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) {
return db.requestGroupGetById(request.parentId).then(requestGroup => {
const environment = requestGroup ? requestGroup.environment : {};
let renderedRequest = null;
if (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, environment);
} catch (e) {
// Failed to render Request
throw new Error(`Render Failed: "${e.message}"`);
}
try {
renderedRequest = JSON.parse(renderedJSON);
} catch (e) {
// Failed to parse rendered request
throw new Error(`Parse Failed: "${e.message}"`);
}
return new Promise(resolve => resolve(renderedRequest));
}
});
}