Skip to content

Commit

Permalink
Merge branch 'post-script-integration' into post-script-tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ihexxa committed Apr 30, 2024
2 parents 76ba136 + 2ef9b24 commit 0826b7f
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 43 deletions.
61 changes: 27 additions & 34 deletions packages/insomnia-sdk/src/objects/response.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { RESPONSE_CODE_REASONS } from 'insomnia/src/common/constants';
import { Compression, ResponseHeader } from 'insomnia/src/models/response';
import { sendCurlAndWriteTimeline } from 'insomnia/src/network/network';
import { type sendCurlAndWriteTimelineResponse, sendCurlAndWriteTimelineError } from 'insomnia/src/network/network';

import { Cookie, CookieOptions } from './cookies';
import { CookieList } from './cookies';
Expand Down Expand Up @@ -188,43 +188,36 @@ export class Response extends Property {

export async function toScriptResponse(
originalRequest: Request,
partialInsoResponse: Awaited<ReturnType<typeof sendCurlAndWriteTimeline>>,
partialInsoResponse: sendCurlAndWriteTimelineResponse | sendCurlAndWriteTimelineError,
): Promise<Response | undefined> {
if (partialInsoResponse.error) {
// response basically doesn't contain anything
if ('error' in partialInsoResponse) {
// it is sendCurlAndWriteTimelineError and basically doesn't contain anything useful
return undefined;
}

// TODO: improve the type from sendCurlAndWriteTimeline a bit
// so that typing in downstream logic could be improved
const partialResponse = partialInsoResponse as {
headers: ResponseHeader[];
bodyPath: string;
bodyCompression: Compression;
statusCode: number;
elapsedTime: number;
statusMessage: string;
};

const headers = partialResponse.headers.map(
insoHeader => ({
key: insoHeader.name,
value: insoHeader.value,
}),
{},
);

const insoCookieOptions = partialResponse.headers
.filter(
header => {
return header.name.toLowerCase() === 'set-cookie';
},
const partialResponse = partialInsoResponse as sendCurlAndWriteTimelineResponse;

const headers = partialResponse.headers ?
partialResponse.headers.map(
insoHeader => ({
key: insoHeader.name,
value: insoHeader.value,
}),
{},
).map(
setCookieHeader => Cookie.parse(setCookieHeader.value)
);
)
: [];

const insoCookieOptions = partialResponse.headers ?
partialResponse.headers
.filter(
header => {
return header.name.toLowerCase() === 'set-cookie';
},
{},
).map(
setCookieHeader => Cookie.parse(setCookieHeader.value)
)
: [];

// TODO: handle default path
let responseBody = '';
if (partialResponse.bodyPath) {
const readResponseResult = await window.bridge.readCurlResponse({
Expand All @@ -240,7 +233,7 @@ export async function toScriptResponse(
}

const responseOption = {
code: partialResponse.statusCode,
code: partialResponse.statusCode || 0,
// reason is not provided
header: headers,
cookie: insoCookieOptions,
Expand Down
75 changes: 70 additions & 5 deletions packages/insomnia/src/network/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ export const fetchRequestData = async (requestId: string) => {
return { request, environment, settings, clientCertificates, caCert, activeEnvironmentId, timelinePath, responseId };
};

export const tryToExecutePreRequestScript = async (
isPreRequest: boolean,
export const tryToExecuteScript = async (
script: string,
request: Request,
environment: Environment,
timelinePath: string,
Expand All @@ -84,13 +84,14 @@ export const tryToExecutePreRequestScript = async (
cookieJar: CookieJar,
response?: Awaited<ReturnType<typeof sendCurlAndWriteTimeline>>,
) => {
if (!request.preRequestScript) {
if (!script) {
return {
request,
environment: undefined,
baseEnvironment: undefined,
};
}

const settings = await models.settings.get();

try {
Expand All @@ -103,7 +104,7 @@ export const tryToExecutePreRequestScript = async (
}, timeout + 1000);
});
const preRequestPromise = cancellableRunPreRequestScript({
script: isPreRequest ? request.preRequestScript : request.postRequestScript,
script,
context: {
request,
timelinePath,
Expand Down Expand Up @@ -175,6 +176,50 @@ export const tryToExecutePreRequestScript = async (
}
};

export async function tryToExecutePreRequestScript(
request: Request,
environment: Environment,
timelinePath: string,
responseId: string,
baseEnvironment: Environment,
clientCertificates: ClientCertificate[],
cookieJar: CookieJar,
) {
return tryToExecuteScript(
request.preRequestScript,
request,
environment,
timelinePath,
responseId,
baseEnvironment,
clientCertificates,
cookieJar,
);
};

export async function tryToExecutePostRequestScript(
request: Request,
environment: Environment,
timelinePath: string,
responseId: string,
baseEnvironment: Environment,
clientCertificates: ClientCertificate[],
cookieJar: CookieJar,
response: sendCurlAndWriteTimelineResponse,
) {
return tryToExecuteScript(
request.postRequestScript,
request,
environment,
timelinePath,
responseId,
baseEnvironment,
clientCertificates,
cookieJar,
response,
);
}

export const tryToInterpolateRequest = async (
request: Request,
environment: string | Environment,
Expand Down Expand Up @@ -208,14 +253,34 @@ export const tryToTransformRequestWithPlugins = async (renderResult: RequestAndC
throw new Error(`Failed to transform request with plugins: ${request._id}`);
}
};

export interface sendCurlAndWriteTimelineError {
_id: string;
parentId: string;
timelinePath: string;
statusMessage: string;
// additional
url: string;
error: string;
elapsedTime: number;
bytesRead: number;
}

export interface sendCurlAndWriteTimelineResponse extends ResponsePatch {
_id: string;
parentId: string;
timelinePath: string;
statusMessage: string;
}

export async function sendCurlAndWriteTimeline(
renderedRequest: RenderedRequest,
clientCertificates: ClientCertificate[],
caCert: CaCertificate | null,
settings: Settings,
timelinePath: string,
responseId: string,
) {
): Promise<sendCurlAndWriteTimelineError | sendCurlAndWriteTimelineResponse> {
const requestId = renderedRequest._id;
const timelineStrings: string[] = [];
const authentication = renderedRequest.authentication as RequestAuthentication;
Expand Down
6 changes: 2 additions & 4 deletions packages/insomnia/src/ui/routes/request.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { Response } from '../../models/response';
import { isWebSocketRequest, isWebSocketRequestId, WebSocketRequest } from '../../models/websocket-request';
import { WebSocketResponse } from '../../models/websocket-response';
import { getAuthHeader } from '../../network/authentication';
import { fetchRequestData, responseTransform, sendCurlAndWriteTimeline, tryToExecutePreRequestScript, tryToInterpolateRequest, tryToTransformRequestWithPlugins } from '../../network/network';
import { fetchRequestData, responseTransform, sendCurlAndWriteTimeline, tryToExecutePostRequestScript, tryToExecutePreRequestScript, tryToInterpolateRequest, tryToTransformRequestWithPlugins } from '../../network/network';
import { RenderErrorSubType } from '../../templating';
import { invariant } from '../../utils/invariant';
import { SegmentEvent } from '../analytics';
Expand Down Expand Up @@ -382,7 +382,6 @@ export const sendAction: ActionFunction = async ({ request, params }) => {
try {
const { shouldPromptForPathAfterResponse, ignoreUndefinedEnvVariable } = await request.json() as SendActionParams;
const mutatedContext = await tryToExecutePreRequestScript(
true,
req,
environment,
timelinePath,
Expand Down Expand Up @@ -437,8 +436,7 @@ export const sendAction: ActionFunction = async ({ request, params }) => {
const is2XXWithBodyPath = responsePatch.statusCode && responsePatch.statusCode >= 200 && responsePatch.statusCode < 300 && responsePatch.bodyPath;
const shouldWriteToFile = shouldPromptForPathAfterResponse && is2XXWithBodyPath;

const postMutatedContext = await tryToExecutePreRequestScript(
false,
const postMutatedContext = await tryToExecutePostRequestScript(
req,
environment,
timelinePath,
Expand Down

0 comments on commit 0826b7f

Please sign in to comment.