insomnia/packages/insomnia-app/app/common/render.ts

550 lines
17 KiB
TypeScript
Raw Normal View History

import clone from 'clone';
2021-07-22 23:04:56 +00:00
import { setDefaultProtocol } from 'insomnia-url';
import orderedJSON from 'json-order';
2016-11-10 05:56:23 +00:00
import * as models from '../models';
2018-06-25 17:42:50 +00:00
import type { CookieJar } from '../models/cookie-jar';
import type { Environment } from '../models/environment';
import type { GrpcRequest, GrpcRequestBody } from '../models/grpc-request';
2021-07-22 23:04:56 +00:00
import type { BaseModel } from '../models/index';
import type { Request } from '../models/request';
import { isRequestGroup } from '../models/request-group';
2021-06-16 21:05:31 +00:00
import { isWorkspace } from '../models/workspace';
2021-07-22 23:04:56 +00:00
import * as templating from '../templating';
import * as templatingUtils from '../templating/utils';
import { CONTENT_TYPE_GRAPHQL, JSON_ORDER_SEPARATOR } from './constants';
import { database as db } from './database';
2016-04-15 02:13:49 +00:00
export const KEEP_ON_ERROR = 'keep';
export const THROW_ON_ERROR = 'throw';
export type RenderPurpose = 'send' | 'general' | 'no-render';
export const RENDER_PURPOSE_SEND: RenderPurpose = 'send';
export const RENDER_PURPOSE_GENERAL: RenderPurpose = 'general';
export const RENDER_PURPOSE_NO_RENDER: RenderPurpose = 'no-render';
/** Key/value pairs to be provided to the render context */
export type ExtraRenderInfo = {
name: string;
value: any;
}[];
export type RenderedRequest = Request & {
cookies: {
name: string;
value: string;
disabled?: boolean;
}[];
cookieJar: CookieJar;
};
export type RenderedGrpcRequest = GrpcRequest;
export type RenderedGrpcRequestBody = GrpcRequestBody;
export interface RenderContextAndKeys {
context: Record<string, any>;
keys: {
name: string;
value: any;
}[]
}
export type HandleGetRenderContext = () => Promise<RenderContextAndKeys>;
export type HandleRender = <T>(object: T, contextCacheKey?: string | null) => Promise<T>;
2018-06-25 17:42:50 +00:00
export async function buildRenderContext(
ancestors: BaseModel[] | null,
rootEnvironment: Environment | null,
subEnvironment: Environment | null,
baseContext: Record<string, any> = {},
) {
const envObjects: Record<string, any>[] = [];
// Get root environment keys in correct order
// Then get sub environment keys in correct order
// Then get ancestor (folder) environment keys in correct order
if (rootEnvironment) {
const ordered = orderedJSON.order(
rootEnvironment.data,
rootEnvironment.dataPropertyOrder,
JSON_ORDER_SEPARATOR,
);
envObjects.push(ordered);
}
if (subEnvironment) {
const ordered = orderedJSON.order(
subEnvironment.data,
subEnvironment.dataPropertyOrder,
JSON_ORDER_SEPARATOR,
);
envObjects.push(ordered);
}
for (const doc of (ancestors || []).reverse()) {
const ancestor: any = doc;
const { environment, environmentPropertyOrder } = ancestor;
2018-03-29 17:59:32 +00:00
if (typeof environment === 'object' && environment !== null) {
const ordered = orderedJSON.order(
environment,
environmentPropertyOrder,
JSON_ORDER_SEPARATOR,
);
envObjects.push(ordered);
}
2017-01-13 19:21:03 +00:00
}
// At this point, environments is a list of environments ordered
// from top-most parent to bottom-most child, and they keys in each environment
// ordered by its property map.
// Do an Object.assign, but render each property as it overwrites. This
// way we can keep same-name variables from the parent context.
let renderContext = baseContext;
// Made the rendering into a recursive function to handle nested Objects
async function renderSubContext(
subObject: Record<string, any>,
subContext: Record<string, any>,
) {
const keys = _getOrderedEnvironmentKeys(subObject);
for (const key of keys) {
/*
* If we're overwriting a string, try to render it first using the same key from the base
* environment to support same-variable recursion. This allows for the following scenario:
*
* base: { base_url: 'google.com' }
* obj: { base_url: '{{ base_url }}/foo' }
* final: { base_url: 'google.com/foo' }
*
* A regular Object.assign would yield { base_url: '{{ base_url }}/foo' } and the
* original base_url of google.com would be lost.
*/
2019-11-22 18:31:23 +00:00
if (Object.prototype.toString.call(subObject[key]) === '[object String]') {
const isSelfRecursive = subObject[key].match(`{{ ?${key}[ |][^}]*}}`);
2018-07-25 20:58:01 +00:00
if (isSelfRecursive) {
// If we're overwriting a variable that contains itself, make sure we
// render it first
subContext[key] = await render(
subObject[key],
subContext, // Only render with key being overwritten
2018-07-25 20:58:01 +00:00
null,
KEEP_ON_ERROR,
'Environment',
2018-07-25 20:58:01 +00:00
);
} else {
// Otherwise it's just a regular replacement
subContext[key] = subObject[key];
2018-07-25 20:58:01 +00:00
}
2019-08-13 15:31:02 +00:00
} else if (Object.prototype.toString.call(subContext[key]) === '[object Object]') {
// Context is of Type object, Call this function recursively to handle nested objects.
subContext[key] = renderSubContext(subObject[key], subContext[key]);
} else {
2019-08-13 15:31:02 +00:00
// For all other Types, add the Object to the Context.
subContext[key] = subObject[key];
}
}
return subContext;
}
for (const envObject of envObjects) {
// For every environment render the Objects
renderContext = await renderSubContext(envObject, renderContext);
}
// Render the context with itself to fill in the rest.
const finalRenderContext = renderContext;
2017-02-07 16:09:12 +00:00
const keys = _getOrderedEnvironmentKeys(finalRenderContext);
// Render recursive references and tags.
const skipNextTime = {};
2017-02-07 16:09:12 +00:00
for (let i = 0; i < 3; i++) {
for (const key of keys) {
// Skip rendering keys that stayed the same multiple times. This is here because
// a render failure will leave the tag as-is and thus the next iteration of the
// loop will try to re-render it again. We don't want to keep erroring on these
// because renders are expensive and potentially not idempotent.
if (skipNextTime[key]) {
continue;
}
const renderResult = await render(
finalRenderContext[key],
finalRenderContext,
null,
KEEP_ON_ERROR,
'Environment',
);
// Result didn't change, so skip
if (renderResult === finalRenderContext[key]) {
skipNextTime[key] = true;
continue;
}
finalRenderContext[key] = renderResult;
}
2017-02-07 16:09:12 +00:00
}
2017-02-07 16:09:12 +00:00
return finalRenderContext;
}
/**
* Recursively render any JS object and return a new one
* @param {*} obj - object to render
* @param {object} context - context to render against
* @param blacklistPathRegex - don't render these paths
* @param errorMode - how to handle errors
* @param name - name to include in error message
* @return {Promise.<*>}
*/
2018-06-25 17:42:50 +00:00
export async function render<T>(
obj: T,
context: Record<string, any> = {},
blacklistPathRegex: RegExp | null = null,
errorMode: string = THROW_ON_ERROR,
name = '',
) {
// Make a deep copy so no one gets mad :)
const newObj = clone(obj);
async function next<T>(x: T, path: string, first = false) {
if (blacklistPathRegex && path.match(blacklistPathRegex)) {
return x;
}
const asStr = Object.prototype.toString.call(x);
// Leave these types alone
if (
asStr === '[object Date]' ||
asStr === '[object RegExp]' ||
asStr === '[object Error]' ||
asStr === '[object Boolean]' ||
asStr === '[object Number]' ||
asStr === '[object Null]' ||
asStr === '[object Undefined]'
) {
// Do nothing to these types
} else if (typeof x === 'string') {
try {
// @ts-expect-error -- TSCONVERSION
2018-06-25 17:42:50 +00:00
x = await templating.render(x, { context, path });
// If the variable outputs a tag, render it again. This is a common use
// case for environment variables:
// {{ foo }} => {% uuid 'v4' %} => dd265685-16a3-4d76-a59c-e8264c16835a
// @ts-expect-error -- TSCONVERSION
if (x.includes('{%')) {
// @ts-expect-error -- TSCONVERSION
2018-06-25 17:42:50 +00:00
x = await templating.render(x, { context, path });
}
} catch (err) {
if (errorMode !== KEEP_ON_ERROR) {
throw err;
}
}
} else if (Array.isArray(x)) {
for (let i = 0; i < x.length; i++) {
x[i] = await next(x[i], `${path}[${i}]`);
}
} else if (typeof x === 'object' && x !== null) {
// Don't even try rendering disabled objects
// Note, this logic probably shouldn't be here, but w/e for now
// @ts-expect-error -- TSCONVERSION
if (x.disabled) {
return x;
}
const keys = Object.keys(x);
for (const key of keys) {
if (first && key.indexOf('_') === 0) {
x[key] = await next(x[key], path);
} else {
const pathPrefix = path ? path + '.' : '';
x[key] = await next(x[key], `${pathPrefix}${key}`);
}
}
}
return x;
}
return next<T>(newObj, name, true);
}
fix node-libcurl imports (#3384) * fix node-libcurl imports * removes unnecessary function wrapper and anyway, `number` is not the correct type (which is what motivated this change in the first place), `CurlFeature` is. * updates type for setOpt see https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgOIBs4GcvIN4BQyxyWwAXhAFzIDkWAtnOurcgD50MQAmwArgzadamKAHMItANwEAvgQKhIsRCgDCAe00BrYCkIlkYAJ4AHanSz9xcKMLoIAFpoSbMkdU+BmZ8xQD0AcjK0PBIyJoAbtDomnA8WErgYWrIAIIIYMCaIPhEJBBwYACMABSaZtm5NLQAssDoOrQANMjimDg0GNhYAJQ0UZrAPLJGRaUVVTkgtVq6+lityG4Ll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2OcRd3df1n3DdFsAvsUjybul-Qg46m3FeRz66dV532bd7WPdIWjcmDJPjZTtbJfNmHs5D23meccO5Uj4uNdjsu+cZI5q5F2vU5KdOobu5unoVk62-ziPgiL9XXd7nW0QHquzhr-3fMznap8BhHXrnjvC6d5eY65vv18r0NfeT1OJ3HxvjwP3PZ-bsG5SAA to see why `any` is required, for now (at least) * updates the getBodyBuffer parse calls now that the types are working * return to prior approach, this time with a warning
2021-05-17 13:59:43 +00:00
2018-06-25 17:42:50 +00:00
export async function getRenderContext(
request: Request | GrpcRequest | null,
environmentId: string | null,
ancestors: BaseModel[] | null = null,
purpose: RenderPurpose | null = null,
extraInfo: ExtraRenderInfo | null = null,
): Promise<Record<string, any>> {
2017-02-13 08:12:02 +00:00
if (!ancestors) {
ancestors = await _getRequestAncestors(request);
2017-02-13 08:12:02 +00:00
}
2021-06-16 21:05:31 +00:00
const workspace = ancestors.find(isWorkspace);
if (!workspace) {
throw new Error('Failed to render. Could not find workspace');
}
const rootEnvironment = await models.environment.getOrCreateForParentId(
workspace ? workspace._id : 'n/a',
2018-06-25 17:42:50 +00:00
);
const subEnvironment = await models.environment.getById(environmentId || 'n/a');
const keySource = {};
// Function that gets Keys and stores their Source location
function getKeySource(subObject, inKey, inSource) {
// Add key to map if it's not root
if (inKey) {
keySource[templatingUtils.normalizeToDotAndBracketNotation(inKey)] = inSource;
}
// Recurse down for Objects and Arrays
const typeStr = Object.prototype.toString.call(subObject);
if (typeStr === '[object Object]') {
for (const key of Object.keys(subObject)) {
getKeySource(subObject[key], templatingUtils.forceBracketNotation(inKey, key), inSource);
}
} else if (typeStr === '[object Array]') {
for (let i = 0; i < subObject.length; i++) {
getKeySource(subObject[i], templatingUtils.forceBracketNotation(inKey, i), inSource);
}
}
}
const inKey = templating.NUNJUCKS_TEMPLATE_GLOBAL_PROPERTY_NAME;
// Get Keys from root environment
getKeySource((rootEnvironment || {}).data, inKey, 'root');
// Get Keys from sub environment
if (subEnvironment) {
getKeySource(subEnvironment.data || {}, inKey, subEnvironment.name || '');
}
// Get Keys from ancestors (e.g. Folders)
if (ancestors) {
for (let idx = 0; idx < ancestors.length; idx++) {
const ancestor: any = ancestors[idx] || {};
if (
isRequestGroup(ancestor) &&
ancestor.hasOwnProperty('environment') &&
ancestor.hasOwnProperty('name')
) {
getKeySource(ancestor.environment || {}, inKey, ancestor.name || '');
}
}
}
// Add meta data helper function
const baseContext: Record<string, any> = {};
baseContext.getMeta = () => ({
requestId: request ? request._id : null,
workspaceId: workspace ? workspace._id : 'n/a',
});
baseContext.getKeysContext = () => ({
keyContext: keySource,
});
baseContext.getPurpose = () => purpose;
baseContext.getExtraInfo = (key: string) => {
if (!Array.isArray(extraInfo)) {
return null;
}
const p = extraInfo.find(v => v.name === key);
return p ? p.value : null;
};
baseContext.getEnvironmentId = () => environmentId;
// Generate the context we need to render
2018-07-25 20:58:01 +00:00
return buildRenderContext(ancestors, rootEnvironment, subEnvironment, baseContext);
2017-02-13 08:12:02 +00:00
}
fix node-libcurl imports (#3384) * fix node-libcurl imports * removes unnecessary function wrapper and anyway, `number` is not the correct type (which is what motivated this change in the first place), `CurlFeature` is. * updates type for setOpt see https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgOIBs4GcvIN4BQyxyWwAXhAFzIDkWAtnOurcgD50MQAmwArgzadamKAHMItANwEAvgQKhIsRCgDCAe00BrYCkIlkYAJ4AHanSz9xcKMLoIAFpoSbMkdU+BmZ8xQD0AcjK0PBIyJoAbtDomnA8WErgYWrIAIIIYMCaIPhEJBBwYACMABSaZtm5NLQAssDoOrQANMjimDg0GNhYAJQ0UZrAPLJGRaUVVTkgtVq6+lityG4LlvN6EAPIQyOyCgRuIFhgyIjVsxlZM8gAvPnjxeWVF208xXB9+MhByGZQmgARugIAwaKYLCFcCBNKdQDBoFBeGcQDxkABJZBOOAxZAw5AAdzgJmMmmM5hQwFOsKc0AJwCwEAKRmIRyw7ggADo4uIyrRzjNORMSss8JFprk3h9kHI+syZf5Drk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-bsG5SAA to see why `any` is required, for now (at least) * updates the getBodyBuffer parse calls now that the types are working * return to prior approach, this time with a warning
2021-05-17 13:59:43 +00:00
export async function getRenderedGrpcRequest(
request: GrpcRequest,
environmentId: string | null,
purpose?: RenderPurpose,
extraInfo?: ExtraRenderInfo,
skipBody?: boolean,
) {
const renderContext = await getRenderContext(
request,
environmentId,
null,
purpose,
extraInfo || null,
);
const description = request.description;
// Render description separately because it's lower priority
request.description = '';
// Ignore body by default and only include if specified to
const ignorePathRegex = skipBody ? /^body.*/ : null;
// Render all request properties
const renderedRequest: RenderedGrpcRequest = await render(
request,
renderContext,
ignorePathRegex,
);
renderedRequest.description = await render(description, renderContext, null, KEEP_ON_ERROR);
return renderedRequest;
}
export async function getRenderedGrpcRequestMessage(
request: GrpcRequest,
environmentId: string | null,
purpose?: RenderPurpose,
extraInfo?: ExtraRenderInfo,
) {
const renderContext = await getRenderContext(
request,
environmentId,
null,
purpose,
extraInfo || null,
);
// Render request body
const renderedBody: RenderedGrpcRequestBody = await render(request.body, renderContext);
return renderedBody;
}
fix node-libcurl imports (#3384) * fix node-libcurl imports * removes unnecessary function wrapper and anyway, `number` is not the correct type (which is what motivated this change in the first place), `CurlFeature` is. * updates type for setOpt see https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgOIBs4GcvIN4BQyxyWwAXhAFzIDkWAtnOurcgD50MQAmwArgzadamKAHMItANwEAvgQKhIsRCgDCAe00BrYCkIlkYAJ4AHanSz9xcKMLoIAFpoSbMkdU+BmZ8xQD0AcjK0PBIyJoAbtDomnA8WErgYWrIAIIIYMCaIPhEJBBwYACMABSaZtm5NLQAssDoOrQANMjimDg0GNhYAJQ0UZrAPLJGRaUVVTkgtVq6+lityG4LlvN6EAPIQyOyCgRuIFhgyIjVsxlZM8gAvPnjxeWVF208xXB9+MhByGZQmgARugIAwaKYLCFcCBNKdQDBoFBeGcQDxkABJZBOOAxZAw5AAdzgJmMmmM5hQwFOsKc0AJwCwEAKRmIRyw7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XrnjvC6d5eY65vv18r0NfeT1OJ3HxvjwP3PZ-bsG5SAA to see why `any` is required, for now (at least) * updates the getBodyBuffer parse calls now that the types are working * return to prior approach, this time with a warning
2021-05-17 13:59:43 +00:00
2018-06-25 17:42:50 +00:00
export async function getRenderedRequestAndContext(
request: Request,
fix node-libcurl imports (#3384) * fix node-libcurl imports * removes unnecessary function wrapper and anyway, `number` is not the correct type (which is what motivated this change in the first place), `CurlFeature` is. * updates type for setOpt see https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgOIBs4GcvIN4BQyxyWwAXhAFzIDkWAtnOurcgD50MQAmwArgzadamKAHMItANwEAvgQKhIsRCgDCAe00BrYCkIlkYAJ4AHanSz9xcKMLoIAFpoSbMkdU+BmZ8xQD0AcjK0PBIyJoAbtDomnA8WErgYWrIAIIIYMCaIPhEJBBwYACMABSaZtm5NLQAssDoOrQANMjimDg0GNhYAJQ0UZrAPLJGRaUVVTkgtVq6+lityG4LlvN6EAPIQyOyCgRuIFhgyIjVsxlZM8gAvPnjxeWVF208xXB9+MhByGZQmgARugIAwaKYLCFcCBNKdQDBoFBeGcQDxkABJZBOOAxZAw5AAdzgJmMmmM5hQwFOsKc0AJwCwEAKRmIRyw7ggADo4uIyrRzjNORMSss8JFprk3h9kHI+syZf5DrkTshhQB1KBwMwWKA0TIXADatGFtAAundkFNXsh3mBPncAHzfX7-IEgsHkyEMvGwkIgBFQJFouCojFYnEofFEklgMkQynUsC0qD0xnytkc7maXnGp6i8XW21wGV9MaFJ4arU6q0zKV20uKgi-JHifhiZAwfgga65SIxKBxBJJTvdi6q4oAJhrNToDSayw6vW6nX6g2GowII57eQmU5eMzm2k2Szaq02NA2+m2uw3W7Hu+nIDr9rFLoBwNB4IpUJ9cP9iOREM0UxbFcSjYlSU9BNIiTOkGRQMpvQAAxDEwkOMWlIhAdASX3XIAH5iHSZAuxuBkQFoU43EDCAslVKlk05OUjAzEEsxzFs2zsDsu23fM8KfG1pVlRU2VOXdK21aAvwsTQYHHMAJwtR9ny+W4nVfYJXQ-D14x-GE-wDIMUWA8MwLJaNIL0qkYOTVMmRY5VMx5Pld2QSSdVoBtHkUlShPrfZAmCWDGUJTQoB0NpsFVAAPCwsl4KgmyCFLUrS9KMsyrKUoIAVciFJ4+TnZo2jFMhKFqRhmFYEtZHVTUpKgIrGhK75yssegmBYNhZTqydmvnUrSAoDqqu62qCAkhrq3qFr83ayqupq3rFDykACsmWhLwgE9vnjWpnFcdxiggLwfB6uV6qraA+W23axX2xwXDcDxTu8XwS0m-qtqPRZ80e2hDpek6zo+kSpuupqfrWe6oIO57js8d6LqCjCdpQAAqHgyQMjGwoiqLcAgOLaMgHgkuyymqepoJkuQAABMAsAAWmJ+KwFZwNwuQQEEg7YAoBVOxW24cBcu3DbymhzZ-opeGjte0GUd+RmWbZ0nOYBKAeb5mABaFiRBAgMWrsa27fqkIaAaBxG3vOz6VaZ1mSayTXud5tE9cF05haNk3vu22WLHl4GkftkTHbVl2OcRd3df1n3DdFsAvsUjybul-Qg46m3FeRz66dV532bd7WPdIWjcmDJPjZTtbJfNmHs5D23meccO5Uj4uNdjsu+cZI5q5F2vU5KdOobu5unoVk62-ziPgiL9XXd7nW0QHquzhr-3fMznap8BhHXrnjvC6d5eY65vv18r0NfeT1OJ3HxvjwP3PZ-bsG5SAA to see why `any` is required, for now (at least) * updates the getBodyBuffer parse calls now that the types are working * return to prior approach, this time with a warning
2021-05-17 13:59:43 +00:00
environmentId?: string | null,
purpose?: RenderPurpose,
extraInfo?: ExtraRenderInfo,
) {
const ancestors = await _getRequestAncestors(request);
2021-06-16 21:05:31 +00:00
const workspace = ancestors.find(isWorkspace);
2017-08-22 22:30:57 +00:00
const parentId = workspace ? workspace._id : 'n/a';
const cookieJar = await models.cookieJar.getOrCreateForParentId(parentId);
const renderContext = await getRenderContext(
request,
fix node-libcurl imports (#3384) * fix node-libcurl imports * removes unnecessary function wrapper and anyway, `number` is not the correct type (which is what motivated this change in the first place), `CurlFeature` is. * updates type for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FcdxiggLwfB6uV6qraA+W23axX2xwXDcDxTu8XwS0m-qtqPRZ80e2hDpek6zo+kSpuupqfrWe6oIO57js8d6LqCjCdpQAAqHgyQMjGwoiqLcAgOLaMgHgkuyymqepoJkuQAABMAsAAWmJ+KwFZwNwuQQEEg7YAoBVOxW24cBcu3DbymhzZ-opeGjte0GUd+RmWbZ0nOYBKAeb5mABaFiRBAgMWrsa27fqkIaAaBxG3vOz6VaZ1mSayTXud5tE9cF05haNk3vu22WLHl4GkftkTHbVl2OcRd3df1n3DdFsAvsUjybul-Qg46m3FeRz66dV532bd7WPdIWjcmDJPjZTtbJfNmHs5D23meccO5Uj4uNdjsu+cZI5q5F2vU5KdOobu5unoVk62-ziPgiL9XXd7nW0QHquzhr-3fMznap8BhHXrnjvC6d5eY65vv18r0NfeT1OJ3HxvjwP3PZ-bsG5SAA to see why `any` is required, for now (at least) * updates the getBodyBuffer parse calls now that the types are working * return to prior approach, this time with a warning
2021-05-17 13:59:43 +00:00
environmentId || null,
ancestors,
purpose,
extraInfo || null,
);
2018-06-28 03:49:40 +00:00
// HACK: Switch '#}' to '# }' to prevent Nunjucks from barfing
2019-12-17 17:16:08 +00:00
// https://github.com/kong/insomnia/issues/895
try {
if (request.body.text && request.body.mimeType === CONTENT_TYPE_GRAPHQL) {
const o = JSON.parse(request.body.text);
o.query = o.query.replace(/#}/g, '# }');
request.body.text = JSON.stringify(o);
}
} catch (err) { }
// Render description separately because it's lower priority
const description = request.description;
request.description = '';
// Render all request properties
const renderResult = await render(
{
_request: request,
_cookieJar: cookieJar,
},
renderContext,
request.settingDisableRenderRequestBody ? /^body.*/ : null,
);
const renderedRequest = renderResult._request;
const renderedCookieJar = renderResult._cookieJar;
renderedRequest.description = await render(description, renderContext, null, KEEP_ON_ERROR);
// Remove disabled params
2018-07-25 20:58:01 +00:00
renderedRequest.parameters = renderedRequest.parameters.filter(p => !p.disabled);
// Remove disabled headers
renderedRequest.headers = renderedRequest.headers.filter(p => !p.disabled);
// Remove disabled body params
if (renderedRequest.body && Array.isArray(renderedRequest.body.params)) {
2018-07-25 20:58:01 +00:00
renderedRequest.body.params = renderedRequest.body.params.filter(p => !p.disabled);
}
// Remove disabled authentication
2018-07-25 20:58:01 +00:00
if (renderedRequest.authentication && renderedRequest.authentication.disabled) {
renderedRequest.authentication = {};
}
// Default the proto if it doesn't exist
renderedRequest.url = setDefaultProtocol(renderedRequest.url);
return {
context: renderContext,
request: {
// Add the yummy cookies
cookieJar: renderedCookieJar,
cookies: [],
2018-03-06 03:15:09 +00:00
isPrivate: false,
// NOTE: Flow doesn't like Object.assign, so we have to do each property manually
// for now to convert Request to RenderedRequest.
_id: renderedRequest._id,
authentication: renderedRequest.authentication,
body: renderedRequest.body,
created: renderedRequest.created,
modified: renderedRequest.modified,
description: renderedRequest.description,
headers: renderedRequest.headers,
metaSortKey: renderedRequest.metaSortKey,
method: renderedRequest.method,
name: renderedRequest.name,
parameters: renderedRequest.parameters,
parentId: renderedRequest.parentId,
2018-07-25 20:58:01 +00:00
settingDisableRenderRequestBody: renderedRequest.settingDisableRenderRequestBody,
settingEncodeUrl: renderedRequest.settingEncodeUrl,
settingSendCookies: renderedRequest.settingSendCookies,
settingStoreCookies: renderedRequest.settingStoreCookies,
settingRebuildPath: renderedRequest.settingRebuildPath,
settingFollowRedirects: renderedRequest.settingFollowRedirects,
type: renderedRequest.type,
url: renderedRequest.url,
},
};
}
/**
* Sort the keys that may have Nunjucks last, so that other keys get
* defined first. Very important if env variables defined in same obj
* (eg. {"foo": "{{ bar }}", "bar": "Hello World!"})
*
* @param v
* @returns {number}
*/
2018-06-25 17:42:50 +00:00
function _nunjucksSortValue(v) {
return v && v.match && v.match(/({{|{%)/) ? 2 : 1;
}
function _getOrderedEnvironmentKeys(finalRenderContext: Record<string, any>): string[] {
return Object.keys(finalRenderContext).sort((k1, k2) => {
const k1Sort = _nunjucksSortValue(finalRenderContext[k1]);
const k2Sort = _nunjucksSortValue(finalRenderContext[k2]);
return k1Sort - k2Sort;
});
}
async function _getRequestAncestors(request: Request | GrpcRequest | null): Promise<BaseModel[]> {
return await db.withAncestors(request, [
models.request.type,
models.grpcRequest.type,
models.requestGroup.type,
models.workspace.type,
]);
}