insomnia/packages/insomnia-app/app/plugins/context/response.js

77 lines
2.2 KiB
JavaScript
Raw Normal View History

// @flow
2018-06-25 17:42:50 +00:00
import type { ResponseHeader } from '../../models/response';
import * as models from '../../models/index';
import fs from 'fs';
2018-06-25 17:42:50 +00:00
import { Readable } from 'stream';
type MaybeResponse = {
parentId?: string,
statusCode?: number,
statusMessage?: string,
bytesRead?: number,
bytesContent?: number,
bodyPath?: string,
elapsedTime?: number,
headers?: Array<ResponseHeader>,
2018-06-25 17:42:50 +00:00
};
2018-06-25 17:42:50 +00:00
export function init(response: MaybeResponse): { response: Object } {
if (!response) {
throw new Error('contexts.response initialized without response');
}
return {
response: {
// TODO: Make this work. Right now it doesn't because _id is
// not generated in network.js
// getId () {
// return response.parentId;
// },
2018-06-25 17:42:50 +00:00
getRequestId(): string {
return response.parentId || '';
},
2018-06-25 17:42:50 +00:00
getStatusCode(): number {
return response.statusCode || 0;
},
2018-06-25 17:42:50 +00:00
getStatusMessage(): string {
return response.statusMessage || '';
},
2018-06-25 17:42:50 +00:00
getBytesRead(): number {
return response.bytesRead || 0;
},
2018-06-25 17:42:50 +00:00
getTime(): number {
return response.elapsedTime || 0;
},
2018-06-25 17:42:50 +00:00
getBody(): Buffer | null {
return models.response.getBodyBuffer(response);
},
2018-06-25 17:42:50 +00:00
getBodyStream(): Readable | null {
return models.response.getBodyStream(response);
},
2018-06-25 17:42:50 +00:00
setBody(body: Buffer) {
// Should never happen but just in case it does...
if (!response.bodyPath) {
throw new Error('Could not set body without existing body path');
}
fs.writeFileSync(response.bodyPath, body);
response.bytesContent = body.length;
},
2018-06-25 17:42:50 +00:00
getHeader(name: string): string | Array<string> | null {
const headers = response.headers || [];
2018-10-17 16:42:33 +00:00
const matchedHeaders = headers.filter(h => h.name.toLowerCase() === name.toLowerCase());
if (matchedHeaders.length > 1) {
return matchedHeaders.map(h => h.value);
} else if (matchedHeaders.length === 1) {
return matchedHeaders[0].value;
} else {
return null;
}
},
2018-06-25 17:42:50 +00:00
hasHeader(name: string): boolean {
return this.getHeader(name) !== null;
},
},
};
}