insomnia/app/models/request.js

361 lines
9.5 KiB
JavaScript
Raw Normal View History

2017-07-18 22:10:57 +00:00
// @flow
2017-07-19 01:55:47 +00:00
import type {BaseModel} from './index';
import {AUTH_BASIC, AUTH_DIGEST, AUTH_NONE, AUTH_NTLM, AUTH_OAUTH_2, AUTH_AWS_IAM, CONTENT_TYPE_FILE, CONTENT_TYPE_FORM_DATA, CONTENT_TYPE_FORM_URLENCODED, CONTENT_TYPE_OTHER, getContentTypeFromHeaders, METHOD_GET} from '../common/constants';
2016-11-10 05:56:23 +00:00
import * as db from '../common/database';
2016-11-10 17:33:28 +00:00
import {getContentTypeHeader} from '../common/misc';
import {buildFromParams, deconstructToParams} from '../common/querystring';
import {GRANT_TYPE_AUTHORIZATION_CODE} from '../network/o-auth-2/constants';
export const name = 'Request';
export const type = 'Request';
export const prefix = 'req';
export const canDuplicate = true;
2017-07-18 22:10:57 +00:00
export type RequestAuthentication = Object;
2017-07-18 23:38:19 +00:00
export type RequestHeader = {
name: string,
value: string,
disabled?: boolean
};
2017-07-18 22:10:57 +00:00
2017-07-18 23:38:19 +00:00
export type RequestParameter = {
2017-07-18 22:10:57 +00:00
name: string,
value: string,
2017-07-18 23:38:19 +00:00
disabled?: boolean,
2017-07-18 22:10:57 +00:00
id?: string,
2017-07-18 23:38:19 +00:00
fileName?: string
};
export type RequestBodyParameter = {
name: string,
value: string,
disabled?: boolean,
id?: string,
fileName?: string
2017-07-18 22:10:57 +00:00
};
export type RequestBody = {
text?: string,
fileName?: string,
2017-07-18 23:38:19 +00:00
params?: Array<RequestBodyParameter>
2017-07-18 22:10:57 +00:00
};
2017-07-19 01:55:47 +00:00
type BaseRequest = {
2017-07-18 22:10:57 +00:00
url: string,
name: string,
description: string,
method: string,
body: RequestBody,
2017-07-18 23:38:19 +00:00
parameters: Array<RequestParameter>,
headers: Array<RequestHeader>,
2017-07-18 22:10:57 +00:00
authentication: RequestAuthentication,
metaSortKey: number,
2017-07-19 01:55:47 +00:00
bodyPath: string,
2017-07-18 22:10:57 +00:00
// Settings
settingStoreCookies: boolean,
settingSendCookies: boolean,
settingDisableRenderRequestBody: boolean,
settingEncodeUrl: boolean
};
2017-07-19 01:55:47 +00:00
export type Request = BaseModel & BaseRequest;
export function init () {
2016-11-10 01:15:27 +00:00
return {
url: '',
name: 'New Request',
description: '',
method: METHOD_GET,
body: {},
parameters: [],
headers: [],
authentication: {},
metaSortKey: -1 * Date.now(),
// Settings
settingStoreCookies: true,
settingSendCookies: true,
settingDisableRenderRequestBody: false,
settingEncodeUrl: true
2016-11-10 01:15:27 +00:00
};
}
2017-07-18 22:10:57 +00:00
export function newAuth (type: string, oldAuth: RequestAuthentication = {}): RequestAuthentication {
switch (type) {
// No Auth
case AUTH_NONE:
return {};
// HTTP Basic Authentication
case AUTH_BASIC:
case AUTH_DIGEST:
case AUTH_NTLM:
return {
type,
disabled: oldAuth.disabled || false,
username: oldAuth.username || '',
password: oldAuth.password || ''
};
// OAuth 2.0
case AUTH_OAUTH_2:
return {type, grantType: GRANT_TYPE_AUTHORIZATION_CODE};
case AUTH_AWS_IAM:
return {
type,
disabled: oldAuth.disabled || false,
accessKeyId: oldAuth.accessKeyId || '',
secretAccessKey: oldAuth.secretAccessKey || ''
};
// Types needing no defaults
default:
return {type};
}
}
2017-07-18 22:10:57 +00:00
export function newBodyNone (): RequestBody {
return {};
}
2017-07-18 22:10:57 +00:00
export function newBodyRaw (rawBody: string, contentType: string): RequestBody {
if (typeof contentType !== 'string') {
return {text: rawBody};
}
const mimeType = contentType.split(';')[0];
return {mimeType, text: rawBody};
}
2017-07-18 23:38:19 +00:00
export function newBodyFormUrlEncoded (parameters: Array<RequestBodyParameter> | null): RequestBody {
// Remove any properties (eg. fileName) that might not fit
parameters = (parameters || []).map(parameter => {
2017-07-18 23:38:19 +00:00
const newParameter: RequestBodyParameter = {
name: parameter.name,
value: parameter.value
};
if (parameter.hasOwnProperty('id')) {
newParameter.id = parameter.id;
}
if (parameter.hasOwnProperty('disabled')) {
newParameter.disabled = parameter.disabled;
} else {
newParameter.disabled = false;
}
return newParameter;
});
return {
mimeType: CONTENT_TYPE_FORM_URLENCODED,
params: parameters
};
}
2017-07-18 22:10:57 +00:00
export function newBodyFile (path: string): RequestBody {
2016-11-22 22:26:52 +00:00
return {
mimeType: CONTENT_TYPE_FILE,
fileName: path
};
2016-11-22 22:26:52 +00:00
}
2017-07-18 23:38:19 +00:00
export function newBodyForm (parameters: Array<RequestBodyParameter>): RequestBody {
return {
mimeType: CONTENT_TYPE_FORM_DATA,
params: parameters || []
};
}
2017-07-18 22:10:57 +00:00
export function migrate (doc: Request): Request {
doc = migrateBody(doc);
doc = migrateWeirdUrls(doc);
doc = migrateAuthType(doc);
return doc;
}
2017-07-18 22:10:57 +00:00
export function create (patch: Object = {}): Promise<Request> {
2016-09-21 20:32:45 +00:00
if (!patch.parentId) {
2017-07-18 22:10:57 +00:00
throw new Error(`New Requests missing \`parentId\`: ${JSON.stringify(patch)}`);
2016-09-21 20:32:45 +00:00
}
return db.docCreate(type, patch);
}
2016-09-21 20:32:45 +00:00
2017-07-18 22:10:57 +00:00
export function getById (id: string): Promise<Request | null> {
return db.get(type, id);
}
2016-09-21 20:32:45 +00:00
2017-07-19 01:55:47 +00:00
export function findByParentId (parentId: string): Promise<Array<Request>> {
return db.find(type, {parentId: parentId});
}
2016-09-21 20:32:45 +00:00
2017-07-18 22:10:57 +00:00
export function update (request: Request, patch: Object): Promise<Request> {
2016-09-21 20:32:45 +00:00
return db.docUpdate(request, patch);
}
2016-09-21 20:32:45 +00:00
2017-07-18 22:10:57 +00:00
export function updateMimeType (
request: Request,
mimeType: string,
doCreate: boolean = false
): Promise<Request> {
let headers = request.headers ? [...request.headers] : [];
2016-11-10 17:33:28 +00:00
const contentTypeHeader = getContentTypeHeader(headers);
2016-09-21 20:32:45 +00:00
// Check if we are converting to/from variants of XML or JSON
let leaveContentTypeAlone = false;
if (contentTypeHeader && mimeType) {
const current = contentTypeHeader.value;
if (current.includes('xml') && mimeType.includes('xml')) {
leaveContentTypeAlone = true;
} else if (current.includes('json') && mimeType.includes('json')) {
leaveContentTypeAlone = true;
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// 1. Update Content-Type header //
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
const hasBody = typeof mimeType === 'string';
if (!hasBody || mimeType === CONTENT_TYPE_OTHER) {
2016-09-21 20:32:45 +00:00
headers = headers.filter(h => h !== contentTypeHeader);
} else if (mimeType && contentTypeHeader && !leaveContentTypeAlone) {
contentTypeHeader.value = mimeType;
} else if (mimeType && !contentTypeHeader) {
headers.push({name: 'Content-Type', value: mimeType});
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// 2. Make a new request body //
// ~~~~~~~~~~~~~~~~~~~~~~~~~~ //
let body;
if (mimeType === request.body.mimeType) {
// Unchanged
body = request.body;
} else if (mimeType === CONTENT_TYPE_FORM_URLENCODED) {
// Urlencoded
body = request.body.params
? newBodyFormUrlEncoded(request.body.params)
2017-07-18 23:38:19 +00:00
: newBodyFormUrlEncoded(deconstructToParams(request.body.text));
} else if (mimeType === CONTENT_TYPE_FORM_DATA) {
// Form Data
body = request.body.params
? newBodyForm(request.body.params)
2017-07-18 23:38:19 +00:00
: newBodyForm(deconstructToParams(request.body.text));
2016-11-22 22:26:52 +00:00
} else if (mimeType === CONTENT_TYPE_FILE) {
// File
body = newBodyFile('');
} else if (typeof mimeType !== 'string') {
// No body
body = newBodyNone();
} else {
// Raw Content-Type (ex: application/json)
body = request.body.params
? newBodyRaw(buildFromParams(request.body.params, false), mimeType)
: newBodyRaw(request.body.text || '', mimeType);
2016-09-21 20:32:45 +00:00
}
// ~~~~~~~~~~~~~~~~~~~~~~~~ //
// 2. create/update request //
// ~~~~~~~~~~~~~~~~~~~~~~~~ //
if (doCreate) {
2017-07-18 22:10:57 +00:00
const newRequest: Request = Object.assign({}, request, {headers, body});
return create(newRequest);
} else {
return update(request, {headers, body});
}
}
2016-09-21 20:32:45 +00:00
2017-07-18 22:10:57 +00:00
export async function duplicate (request: Request): Promise<Request> {
2016-09-21 20:32:45 +00:00
const name = `${request.name} (Copy)`;
// Get sort key of next request
const q = {metaSortKey: {$gt: request.metaSortKey}};
const [nextRequest] = await db.find(type, q, {metaSortKey: 1});
const nextSortKey = nextRequest ? nextRequest.metaSortKey : request.metaSortKey + 100;
// Calculate new sort key
const sortKeyIncrement = (nextSortKey - request.metaSortKey) / 2;
const metaSortKey = request.metaSortKey + sortKeyIncrement;
return db.duplicate(request, {name, metaSortKey});
}
2016-09-21 20:32:45 +00:00
2017-07-18 22:10:57 +00:00
export function remove (request: Request): Promise<void> {
2016-09-21 20:32:45 +00:00
return db.remove(request);
}
export function all () {
return db.all(type);
}
// ~~~~~~~~~~ //
// Migrations //
// ~~~~~~~~~~ //
/**
* Migrate old body (string) to new body (object)
* @param request
* @returns {*}
*/
2017-07-18 22:10:57 +00:00
function migrateBody (request: Request): Request {
2016-12-01 18:48:49 +00:00
if (request.body && typeof request.body === 'object') {
return request;
}
// Second, convert all existing urlencoded bodies to new format
const contentType = getContentTypeFromHeaders(request.headers) || '';
const wasFormUrlEncoded = !!contentType.match(/^application\/x-www-form-urlencoded/i);
if (wasFormUrlEncoded) {
// Convert old-style form-encoded request bodies to new style
2017-07-18 22:10:57 +00:00
const body = typeof request.body === 'string' ? request.body : '';
2017-07-18 23:38:19 +00:00
request.body = newBodyFormUrlEncoded(deconstructToParams(body, false));
2016-12-01 18:48:49 +00:00
} else if (!request.body && !contentType) {
request.body = {};
} else {
2017-07-18 22:10:57 +00:00
const body: string = typeof request.body === 'string' ? request.body : '';
request.body = newBodyRaw(body, contentType);
}
return request;
}
/**
* Fix some weird URLs that were caused by an old bug
* @param request
* @returns {*}
*/
2017-07-18 22:10:57 +00:00
function migrateWeirdUrls (request: Request): Request {
// Some people seem to have requests with URLs that don't have the indexOf
// function. This should clear that up. This can be removed at a later date.
if (typeof request.url !== 'string') {
request.url = '';
}
return request;
}
/**
* Ensure the request.authentication.type property is added
* @param request
* @returns {*}
*/
2017-07-18 22:10:57 +00:00
function migrateAuthType (request: Request): Request {
const isAuthSet = request.authentication && request.authentication.username;
if (isAuthSet && !request.authentication.type) {
request.authentication.type = AUTH_BASIC;
}
return request;
}