Duplicate folder and more DB tests

This commit is contained in:
Gregory Schier 2016-09-07 23:54:35 -07:00
parent 0fb7b31667
commit 4ed1170dd7
10 changed files with 305 additions and 70 deletions

View File

@ -95,7 +95,7 @@ class App extends Component {
return;
}
db.requestCopyAndActivate(workspace, request);
db.requestDuplicateAndActivate(workspace, request);
}
}
}

View File

@ -2,6 +2,7 @@ import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux'
import Dropdown from '../components/base/Dropdown';
import DropdownHint from '../components/base/DropdownHint';
import DropdownDivider from '../components/base/DropdownDivider';
import EnvironmentEditModal from '../components/modals/EnvironmentEditModal';
import PromptModal from '../components/modals/PromptModal';
import * as db from '../database';
@ -32,6 +33,11 @@ class RequestGroupActionsDropdown extends Component {
});
}
_requestGroupDuplicate () {
const {requestGroup} = this.props;
db.requestGroupDuplicate(requestGroup)
}
_getActiveWorkspace (props) {
// TODO: Factor this out into a selector
@ -59,6 +65,12 @@ class RequestGroupActionsDropdown extends Component {
<DropdownHint char="N"></DropdownHint>
</button>
</li>
<DropdownDivider />
<li>
<button onClick={e => this._requestGroupDuplicate()}>
<i className="fa fa-copy"></i> Duplicate
</button>
</li>
<li>
<button onClick={e => this._promptUpdateName()}>
<i className="fa fa-edit"></i> Rename
@ -69,11 +81,6 @@ class RequestGroupActionsDropdown extends Component {
<i className="fa fa-code"></i> Environment
</button>
</li>
{/*<li>*/}
{/*<button onClick={e => db.requestGroupCreate({parentId: requestGroup._id})}>*/}
{/*<i className="fa fa-folder"></i> New Folder*/}
{/*</button>*/}
{/*</li>*/}
<li>
<button onClick={e => db.requestGroupRemove(requestGroup)}>
<i className="fa fa-trash-o"></i> Delete

View File

@ -0,0 +1,42 @@
import {TYPE_REQUEST_GROUP, TYPE_REQUEST, TYPE_WORKSPACE} from '../index';
module.exports[TYPE_WORKSPACE] = [{
_id: 'wrk_1',
name: 'Wrk 1'
}];
module.exports[TYPE_REQUEST_GROUP] = [{
_id: 'fld_1',
parentId: 'wrk_1',
name: 'Fld 1'
}, {
_id: 'fld_2',
parentId: 'wrk_1',
name: 'Fld 2'
}, {
_id: 'fld_3',
parentId: 'fld_1',
name: 'Fld 3'
}];
module.exports[TYPE_REQUEST] = [{
_id: 'req_1',
parentId: 'fld_1',
name: 'Req 1'
}, {
_id: 'req_2',
parentId: 'fld_1',
name: 'Req 2'
}, {
_id: 'req_3',
parentId: 'wrk_1',
name: 'Req 3'
}, {
_id: 'req_4',
parentId: 'fld_3',
name: 'Req 4'
}, {
_id: 'req_5',
parentId: 'wrk_1',
name: 'Req 5'
}];

View File

@ -1,9 +1,19 @@
import * as db from '../';
import {PREVIEW_MODE_SOURCE} from '../../lib/previewModes';
function loadFixture (name) {
const fixtures = require(`../__fixtures__/${name}`);
const promises = [];
for (const type of Object.keys(fixtures)) {
for (const doc of fixtures[type]) {
promises.push(db.insert(Object.assign({}, doc, {type})));
}
}
}
describe('requestCreate()', () => {
beforeEach(() => {
return db.initDB({inMemoryOnly: true})
return db.initDB({inMemoryOnly: true}, true);
});
it('creates a valid request', () => {
@ -39,3 +49,54 @@ describe('requestCreate()', () => {
expect(fn).toThrowError('New Requests missing `parentId`');
});
});
describe('requestGroupDuplicate()', () => {
beforeEach(() => {
return Promise.all([
db.initDB({inMemoryOnly: true}, true),
loadFixture('nestedfolders')
]);
});
it('duplicates a RequestGroup', () => {
return new Promise((resolve, reject) => {
db.requestGroupGetById('fld_1').then(requestGroup => {
expect(requestGroup.name).toBe('Fld 1');
db.requestGroupDuplicate(requestGroup).then(newRequestGroup => {
expect(newRequestGroup._id).not.toBe(requestGroup._id);
expect(newRequestGroup.name).toBe('Fld 1 (Copy)');
Promise.all([
db.requestAll(),
db.requestGroupAll(),
db.requestFindByParentId(requestGroup._id),
db.requestGroupFindByParentId(requestGroup._id),
db.requestFindByParentId(newRequestGroup._id),
db.requestGroupFindByParentId(newRequestGroup._id)
]).then(([
allRequests,
allRequestGroups,
childRequests,
childRequestGroups,
newChildRequests,
newChildRequestGroups
]) => {
// This asserting is pretty garbage but it at least checks
// to see that the recursion worked (for the most part)
expect(allRequests.length).toBe(8);
expect(allRequestGroups.length).toBe(5);
expect(childRequests.length).toBe(2);
expect(childRequestGroups.length).toBe(1);
expect(newChildRequests.length).toBe(2);
expect(newChildRequestGroups.length).toBe(1);
resolve();
}, reject);
}, reject)
}, reject);
})
})
});

View File

@ -16,6 +16,10 @@ export const TYPE_REQUEST_GROUP = 'RequestGroup';
export const TYPE_REQUEST = 'Request';
export const TYPE_RESPONSE = 'Response';
export const CHANGE_INSERT = 'insert';
export const CHANGE_UPDATE = 'update';
export const CHANGE_REMOVE = 'remove';
const BASE_MODEL_DEFAULTS = () => ({
modified: Date.now(),
@ -23,7 +27,18 @@ const BASE_MODEL_DEFAULTS = () => ({
parentId: null
});
const MODEL_DEFAULTS = {
const MODEL_ID_PREFIXES = {
[TYPE_STATS]: 'sta',
[TYPE_SETTINGS]: 'set',
[TYPE_WORKSPACE]: 'wrk',
[TYPE_ENVIRONMENT]: 'env',
[TYPE_COOKIE_JAR]: 'jar',
[TYPE_REQUEST_GROUP]: 'fld',
[TYPE_REQUEST]: 'req',
[TYPE_RESPONSE]: 'res'
};
export const MODEL_DEFAULTS = {
[TYPE_STATS]: () => ({
lastLaunch: Date.now(),
lastVersion: null,
@ -101,9 +116,9 @@ function getDBFilePath (modelType) {
* @returns {Promise}
*/
let initialized = false;
export function initDB (config = {}) {
export function initDB (config = {}, force = false) {
// Only init once
if (initialized) {
if (initialized && !force) {
return Promise.resolve();
}
@ -146,8 +161,12 @@ export function offChange (id) {
delete changeListeners[id];
}
function notifyOfChange (event, doc) {
Object.keys(changeListeners).map(k => changeListeners[k](event, doc));
}
function getMostRecentlyModified (type, query = {}) {
return new Promise((resolve, reject) => {
return new Promise(resolve => {
db[type].find(query).sort({modified: -1}).limit(1).exec((err, docs) => {
resolve(docs.length ? docs[0] : null);
})
@ -209,7 +228,7 @@ function count (type, query = {}) {
});
}
function insert (doc) {
export function insert (doc) {
return new Promise((resolve, reject) => {
db[doc.type].insert(doc, (err, newDoc) => {
if (err) {
@ -217,7 +236,7 @@ function insert (doc) {
}
resolve(newDoc);
Object.keys(changeListeners).map(k => changeListeners[k]('insert', doc));
notifyOfChange(CHANGE_INSERT, doc);
});
});
}
@ -230,22 +249,20 @@ function update (doc) {
}
resolve(doc);
Object.keys(changeListeners).map(k => changeListeners[k]('update', doc));
notifyOfChange(CHANGE_UPDATE, doc);
});
});
}
function remove (doc) {
return new Promise(resolve => {
withChildren(doc).then(docs => {
withDescendants(doc).then(docs => {
const promises = docs.map(d => (
db[d.type].remove({_id: d._id}, {multi: true})
));
Promise.all(promises).then(() => {
for (const doc of docs) {
Object.keys(changeListeners).map(k => changeListeners[k]('remove', doc));
}
docs.map(d => notifyOfChange(CHANGE_REMOVE, d));
resolve()
});
});
@ -281,7 +298,13 @@ function docUpdate (originalDoc, patch = {}) {
return update(doc);
}
function docCreate (type, idPrefix, patch = {}) {
function docCreate (type, patch = {}) {
const idPrefix = MODEL_ID_PREFIXES[type];
if (!idPrefix) {
throw new Error(`No ID prefix for ${type}`)
}
const doc = Object.assign(
BASE_MODEL_DEFAULTS(),
{_id: generateId(idPrefix)},
@ -302,7 +325,7 @@ function docCreate (type, idPrefix, patch = {}) {
// GENERAL //
// ~~~~~~~ //
export function withChildren (doc = null) {
export function withDescendants (doc = null) {
let docsToReturn = doc ? [doc] : [];
const next = (docs) => {
@ -339,6 +362,42 @@ export function withChildren (doc = null) {
return next([doc]);
}
export function duplicate (originalDoc, patch = {}) {
return new Promise((resolve, reject) => {
// 1. Copy the doc
const newDoc = Object.assign({}, originalDoc, patch);
delete newDoc._id;
delete newDoc.created;
delete newDoc.modified;
docCreate(newDoc.type, newDoc).then(createdDoc => {
// 2. Get all the children
const promises = [];
for (const type of ALL_TYPES) {
const parentId = originalDoc._id;
const promise = find(type, {parentId});
promises.push(promise);
}
Promise.all(promises).then(results => {
let duplicatePromises = [];
// Gather up the docs from each type
for (const docs of results) {
for (const doc of docs) {
duplicatePromises.push(duplicate(doc, {parentId: createdDoc._id}));
}
}
// 3. Also duplicate all children, and recurse
Promise.all(duplicatePromises).then(() => resolve(createdDoc), reject)
})
})
})
}
// ~~~~~~~ //
// REQUEST //
@ -350,7 +409,7 @@ export function requestCreateAndActivate (workspace, patch = {}) {
})
}
export function requestCopyAndActivate (workspace, request) {
export function requestDuplicateAndActivate (workspace, request) {
return requestDuplicate(request).then(r => {
workspaceUpdate(workspace, {metaActiveRequestId: r._id});
})
@ -361,7 +420,7 @@ export function requestCreate (patch = {}) {
throw new Error('New Requests missing `parentId`', patch);
}
return docCreate(TYPE_REQUEST, 'req', patch);
return docCreate(TYPE_REQUEST, patch);
}
export function requestGetById (id) {
@ -396,12 +455,7 @@ export function requestUpdateContentType (request, contentType) {
export function requestDuplicate (request) {
const name = `${request.name} (Copy)`;
const newRequest = Object.assign({}, request, {name});
// Remove the old Id
delete newRequest._id;
return requestCreate(newRequest);
return duplicate(request, {name});
}
export function requestRemove (request) {
@ -449,7 +503,7 @@ export function requestGroupCreate (patch = {}) {
throw new Error('New Requests missing `parentId`', patch);
}
return docCreate(TYPE_REQUEST_GROUP, 'fdr', patch);
return docCreate(TYPE_REQUEST_GROUP, patch);
}
export function requestGroupUpdate (requestGroup, patch) {
@ -472,6 +526,11 @@ export function requestGroupAll () {
return all(TYPE_REQUEST_GROUP);
}
export function requestGroupDuplicate (requestGroup) {
const name = `${requestGroup.name} (Copy)`;
return duplicate(requestGroup, {name});
}
// ~~~~~~~~ //
// RESPONSE //
@ -483,11 +542,7 @@ export function responseCreate (patch = {}) {
}
removeBulkSilently(TYPE_RESPONSE, {parentId: patch.parentId});
return docCreate(TYPE_RESPONSE, 'res', patch);
}
export function responseAll () {
return all(TYPE_RESPONSE);
return docCreate(TYPE_RESPONSE, patch);
}
export function responseGetLatestByParentId (parentId) {
@ -500,7 +555,7 @@ export function responseGetLatestByParentId (parentId) {
// ~~~~~~~ //
export function cookieJarCreate (patch = {}) {
return docCreate(TYPE_COOKIE_JAR, 'jar', patch);
return docCreate(TYPE_COOKIE_JAR, patch);
}
export function cookieJarGetOrCreateForWorkspace (workspace) {
@ -536,7 +591,7 @@ export function workspaceGetById (id) {
}
export function workspaceCreate (patch = {}) {
return docCreate(TYPE_WORKSPACE, 'wrk', patch);
return docCreate(TYPE_WORKSPACE, patch);
}
export function workspaceAll () {
@ -571,7 +626,7 @@ export function environmentCreate (patch = {}) {
throw new Error('New Environment missing `parentId`', patch);
}
return docCreate(TYPE_ENVIRONMENT, 'env', patch);
return docCreate(TYPE_ENVIRONMENT, patch);
}
export function environmentUpdate (environment, patch) {
@ -611,7 +666,7 @@ export function environmentAll () {
// ~~~~~~~~ //
export function settingsCreate (patch = {}) {
return docCreate(TYPE_SETTINGS, 'set', patch);
return docCreate(TYPE_SETTINGS, patch);
}
export function settingsUpdate (settings, patch) {
@ -633,7 +688,7 @@ export function settingsGetOrCreate () {
// ~~~~~ //
export function statsCreate (patch = {}) {
return docCreate(TYPE_STATS, 'sta', patch);
return docCreate(TYPE_STATS, patch);
}
export function statsUpdate (patch) {

View File

@ -0,0 +1,69 @@
import * as networkUtils from '../network';
import * as db from '../../database';
import {getRenderedRequest} from '../render';
describe('buildRequestConfig()', () => {
beforeEach(() => db.initDB({inMemoryOnly: true}, true));
it('builds a default config', () => {
return db.workspaceCreate().then(workspace => {
const request = Object.assign(db.MODEL_DEFAULTS[db.TYPE_REQUEST](), {
parentId: workspace._id
});
return getRenderedRequest(request).then(renderedRequest => {
const config = networkUtils._buildRequestConfig(renderedRequest);
expect(config).toEqual({
body: '',
followAllRedirects: true,
gzip: true,
headers: {},
maxRedirects: 20,
method: 'GET',
proxy: null,
rejectUnauthorized: true,
time: true,
timeout: 0,
url: 'http://'
});
});
})
});
it('builds a complex config', () => {
return db.workspaceCreate().then(workspace => {
const request = Object.assign(db.MODEL_DEFAULTS[db.TYPE_REQUEST](), {
parentId: workspace._id,
headers: [{name: 'Content-Type', value: 'application/json'}],
parameters: [{name: 'foo bar', value: 'hello&world'}],
method: 'POST',
body: 'foo=bar',
url: 'http://foo.com?bar=baz',
authentication: {
username: 'user',
password: 'pass'
}
});
return getRenderedRequest(request).then(renderedRequest => {
const config = networkUtils._buildRequestConfig(renderedRequest);
expect(config).toEqual({
body: 'foo=bar',
followAllRedirects: true,
gzip: true,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic dXNlcjpwYXNz'
},
maxRedirects: 20,
method: 'POST',
proxy: null,
rejectUnauthorized: true,
time: true,
timeout: 0,
url: 'http://foo.com/?bar=baz&foo%20bar=hello%26world'
});
});
})
});
});

View File

@ -73,7 +73,7 @@ export function exportJSON (parentDoc = null) {
};
return new Promise(resolve => {
db.withChildren(parentDoc).then(docs => {
db.withDescendants(parentDoc).then(docs => {
data.resources = docs.filter(d => (
d.type !== db.TYPE_RESPONSE &&
d.type !== db.TYPE_STATS &&

View File

@ -1,15 +1,13 @@
import networkRequest from 'request';
import {parse as urlParse, format as urlFormat} from 'url';
import * as db from '../database';
import * as querystring from './querystring';
import {DEBOUNCE_MILLIS} from './constants';
import {STATUS_CODE_PEBKAC} from './constants';
import {DEBOUNCE_MILLIS, STATUS_CODE_PEBKAC} from './constants';
import {getRenderedRequest} from './render';
import {jarFromCookies, cookiesFromJar} from './cookies';
function buildRequestConfig (renderedRequest, patch = {}) {
export function _buildRequestConfig (renderedRequest, patch = {}) {
const config = {
method: renderedRequest.method,
body: renderedRequest.body,
@ -39,7 +37,7 @@ function buildRequestConfig (renderedRequest, patch = {}) {
// Encode path portion of URL
const parsedUrl = urlParse(url);
parsedUrl.pathname = encodeURI(parsedUrl.pathname);
parsedUrl.pathname = encodeURI(parsedUrl.pathname || '');
config.url = urlFormat(parsedUrl);
for (let i = 0; i < renderedRequest.headers.length; i++) {
@ -52,7 +50,7 @@ function buildRequestConfig (renderedRequest, patch = {}) {
return Object.assign(config, patch);
}
function actuallySend (renderedRequest, settings) {
export function _actuallySend (renderedRequest, settings) {
return new Promise((resolve, reject) => {
const cookieJar = renderedRequest.cookieJar;
const jar = jarFromCookies(cookieJar.cookies);
@ -63,7 +61,7 @@ function actuallySend (renderedRequest, settings) {
const proxyHost = protocol === 'https:' ? settings.httpsProxy : settings.httpProxy;
const proxy = proxyHost ? `${protocol}//${proxyHost}` : null;
let config = buildRequestConfig(renderedRequest, {
let config = _buildRequestConfig(renderedRequest, {
jar: jar,
proxy: proxy,
followAllRedirects: settings.followRedirects,
@ -134,23 +132,22 @@ function actuallySend (renderedRequest, settings) {
export function send (requestId) {
return new Promise((resolve, reject) => {
// First, lets wait for all debounces to finish
setTimeout(() => {
Promise.all([
db.requestGetById(requestId),
db.settingsGetOrCreate()
]).then(([request, settings]) => {
getRenderedRequest(request).then(renderedRequest => {
actuallySend(renderedRequest, settings).then(resolve, reject);
}, err => {
db.responseCreate({
parentId: request._id,
statusCode: STATUS_CODE_PEBKAC,
error: err.message
}).then(resolve, reject);
});
})
}, DEBOUNCE_MILLIS);
}
)
// First, lets wait for all debounces to finish
setTimeout(() => {
Promise.all([
db.requestGetById(requestId),
db.settingsGetOrCreate()
]).then(([request, settings]) => {
getRenderedRequest(request).then(renderedRequest => {
_actuallySend(renderedRequest, settings).then(resolve, reject);
}, err => {
db.responseCreate({
parentId: request._id,
statusCode: STATUS_CODE_PEBKAC,
error: err.message
}).then(resolve, reject);
});
})
}, DEBOUNCE_MILLIS);
})
}

View File

@ -1,6 +1,9 @@
import {bindActionCreators} from 'redux';
import * as entitiesActions from './modules/entities';
import * as db from '../database';
import {CHANGE_INSERT} from '../database/index';
import {CHANGE_UPDATE} from '../database/index';
import {CHANGE_REMOVE} from '../database/index';
const CHANGE_ID = 'store.listener';
@ -14,11 +17,11 @@ export function initStore (dispatch) {
return;
}
if (event === 'insert') {
if (event === CHANGE_INSERT) {
entities.insert(doc);
} else if (event === 'update') {
} else if (event === CHANGE_UPDATE) {
entities.update(doc);
} else if (event === 'remove') {
} else if (event === CHANGE_REMOVE) {
entities.remove(doc);
}
};
@ -40,7 +43,7 @@ export function initStore (dispatch) {
docs = Array.isArray(docs) ? docs : [docs];
for (let doc of docs) {
docChanged('update', doc);
docChanged(CHANGE_UPDATE, doc);
}
}

View File

@ -12,6 +12,7 @@
},
"scripts": {
"test": "jest --silent",
"test-watch": "jest --watch",
"start-hot": "cross-env HOT=1 INSOMNIA_ENV=development electron -r babel-register ./app/app.js",
"hot-server": "babel-node ./webpack/server.js",
"dev": "concurrently --kill-others \"npm run hot-server\" \"npm run start-hot\"",