Skip to content

Commit

Permalink
Merge pull request #34 from smollweide/develop
Browse files Browse the repository at this point in the history
v0.14.0
  • Loading branch information
smollweide authored May 14, 2017
2 parents c948890 + c97bece commit d69e781
Show file tree
Hide file tree
Showing 32 changed files with 816 additions and 204 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.idea
yarn.lock
node_modules
/preferences.json
/demo/rest/*/*/*/mock/response.txt
Expand Down
8 changes: 8 additions & 0 deletions demo/rest/_collections/bug12.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "NUM-12",
"description": "Sticky header - see spec for details",
"selectedResponses": {
"products/#{productCode}/GET": "success",
"products/#search/GET": "error"
}
}
2 changes: 1 addition & 1 deletion demo/rest/products/#/GET/desc.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@
"type": "application/json"
}
}
}
}
5 changes: 5 additions & 0 deletions doc/readme-collections.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

# Collections

Collections allow you to store your current selected responses and share it with your team members.
For that you can use the UI or the both [CLI commands](/readme.md#L113).
52 changes: 45 additions & 7 deletions lib/UserInterface.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

var Utils = require('./Utils.js');
var extend = require('util')._extend;
var ignoreInRestRoot = require('./constants/ignore-in-rest-root');

/**
* @constructor UserInterface
Expand All @@ -27,13 +28,15 @@ UserInterface.prototype = extend(UserInterface.prototype, {
this.options = options;
this._data = [];
this._dataDto = [];
this._dataCollections = [];
this._swaggerImport = this._readSwaggerImportFile();
this._validation = this._readValidationFile();
this._isSwaggerImportAvailable = (typeof options.swaggerImport === 'object');
this._isCustomDTOToClassAvailable = (typeof options.customDTOToClassTemplate === 'string');

this._readApi();
this._readDtos();
this._readCollections();
},

/**
Expand All @@ -45,6 +48,7 @@ UserInterface.prototype = extend(UserInterface.prototype, {
switch (type) {
case 'data': return this._data;
case 'dataDto': return this._dataDto;
case 'dataCollections': return this._dataCollections;
case 'swaggerImport': return this._swaggerImport;
case 'validation': return this._validation;
case 'isSwaggerImportAvailable': return this._isSwaggerImportAvailable;
Expand Down Expand Up @@ -78,6 +82,42 @@ UserInterface.prototype = extend(UserInterface.prototype, {
}.bind(this));
},

/**
* @method _readCollections
* @returns {void}
* @private
*/
_readCollections: function () {

var path = this.options.restPath + '/_collections';
var files = this.readDir(path, ['.DS_Store']);

this._dataCollections.push({
name: 'Reset',
id: 'reset',
description: 'will remove all "response.txt" files.',
isDeleteable: false,
isOpenable: false,
});

this.for(files, function (item) {
this._dataCollections.push(this._readCollection(path, item.file));
}.bind(this));
},

/**
* @param {string} path - the dto directory
* @param {string} fileName - the collection fileName
* @returns {Object} the collection response
* @private
*/
_readCollection: function (path, fileName) {
var collectionData = JSON.parse(this.readFile(path + '/' + fileName));
collectionData.id = fileName.replace(/\.json$/, '');
collectionData.path = path + '/' + fileName;
return collectionData;
},

/**
* @param {string} path - the dto directory
* @param {string} fileName - the dto fileName
Expand Down Expand Up @@ -118,13 +158,7 @@ UserInterface.prototype = extend(UserInterface.prototype, {
var files = [];

try {
files = this.readDir(this.options.restPath, [
'_DTO',
'.DS_Store',
'preferences.json',
'.swagger_import.json',
'.validation.json',
]);
files = this.readDir(this.options.restPath, ignoreInRestRoot);
} catch (err) {
files = [];
}
Expand Down Expand Up @@ -361,6 +395,10 @@ UserInterface.prototype = extend(UserInterface.prototype, {
break;
}

desc.requestFilePath = itemPath + '/request_schema.json';
desc.responseFilePath = itemPath + '/response_schema.json';
desc.descFilePath = itemPath + '/desc.json';

if (desc.request && desc.request.schema) {
desc.request.schema.url = this._getSchemaUrl({
isRequest: true,
Expand Down
18 changes: 16 additions & 2 deletions lib/Utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ Utils.prototype = {

/**
*
* @method writeFile
* @method readDir
* @param {string} dir
* @param {Array|undefined} ignoreFiles
* @public
Expand All @@ -188,7 +188,7 @@ Utils.prototype = {
var results = [];
var list = [];

ignoreFiles = ignoreFiles || [];
ignoreFiles = ignoreFiles || ['.DS_Store'];

try {
list = fs.readdirSync(dir);
Expand Down Expand Up @@ -369,6 +369,20 @@ Utils.prototype = {
return path.replace(options.restPath, '');
},

/**
*
* @method cleanString
* @param {string} value
* @returns {string}
* @public
*/
cleanString: function (value) {
if (!this.isFilledString(value)) {
return undefined;
}
return value.toLowerCase().replace(/[^a-z0-9]/g, '');
},

};

module.exports = Utils;
10 changes: 6 additions & 4 deletions lib/ValidatorResponses.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ var extend = require('util')._extend;
var validatorLog = require('./ValidatorLog');
var ValidatorResponse = require('./ValidatorResponse');
var Utils = require('./Utils');
var ignoreInRestRoot = require('./constants/ignore-in-rest-root');
var ignoreGeneral = require('./constants/ignore-general');

/**
* @constructor ValidatorResponses
Expand Down Expand Up @@ -121,21 +123,21 @@ ValidatorResponses.prototype = extend(ValidatorResponses.prototype, {
*/
_getValidationResponses: function (path) {
var out = [];
var rootDirArray = this.readDir(path, ['.DS_Store', '_DTO', '.validation.json', 'preferences.json']);
var rootDirArray = this.readDir(path, ignoreInRestRoot);

this.for(rootDirArray, function (rootItem) {

var pathDirArray = this.readDir(rootItem.path, ['.DS_Store']);
var pathDirArray = this.readDir(rootItem.path, ignoreGeneral);
this.for(pathDirArray, function (pathItem) {

var pathItemPath = pathItem.path;

var methodDirArray = this.readDir(pathItemPath, ['.DS_Store']);
var methodDirArray = this.readDir(pathItemPath, ignoreGeneral);
this.for(methodDirArray, function (methodItem) {

var method = methodItem.file;

var mockDirArray = this.readDir(methodItem.path + '/mock', ['.DS_Store', 'response.txt']);
var mockDirArray = this.readDir(methodItem.path + '/mock', ignoreGeneral.concat(['response.txt']));
this.for(mockDirArray, function (mockItem) {

var isErrorFile = (mockItem.file.search(/error/g) >= 0);
Expand Down
37 changes: 37 additions & 0 deletions lib/cli/collections-cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/* eslint no-console: 0 */

var log = require('chip')();
var Utils = require('./../Utils');
var utils = new Utils();
var activateCollection = require('../commands/activate-collection');
var util = require('util');
var extend = util._extend;
var _defaults = require('../defaults/options-defaults');

function activateCollectionCli(options) {
options = extend(_defaults, options || {});
if (activateCollection(process.argv[3], options)) {
log(`collection "${process.argv[3]}" activated`);
}
}

function collectionsCli(options) {

var path = `${options.restPath}/_collections`;

console.log('AVAILABLE COLLECTIONS:');
console.log('- reset');
utils.readDir(path).forEach(function (dirItem) {
console.log(`- ${dirItem.file.replace('.json', '')}`);
});
}

var exportFunc;

if (process.argv.length > 3) {
exportFunc = activateCollectionCli;
} else {
exportFunc = collectionsCli;
}

module.exports = exportFunc;
8 changes: 5 additions & 3 deletions lib/cli/help-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ function helpCli() {
console.log('usage with demo: node demo/index.js [--version] [--help] <command> [<args>]');
console.log('');
console.log('node-mock-server commands:');
console.log(' --version print node-mock-server version');
console.log(' swagger-import run a swagger import');
console.log(' validate run a validation for all mock data');
console.log(' --version print node-mock-server version');
console.log(' swagger-import run a swagger import');
console.log(' validate run a validation for all mock data');
console.log(' collections lists all available collections');
console.log(' collections <id> activate collection');
console.log('');
}

Expand Down
57 changes: 57 additions & 0 deletions lib/commands/activate-collection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use strict';

var log = require('chip')();
var Utils = require('../Utils');
var utils = new Utils();
var getCollection = require('./get-collection');
var ignoreInRestRoot = require('../constants/ignore-in-rest-root');

function activateCollection(id, options) {

if (!utils.isFilledString(id)) {
return false;
}

var collection;

if (id === 'reset') {
collection = {
selectedResponses: {},
};
} else {
collection = getCollection(id, options);
}

if (!collection || !collection.selectedResponses) {
return true;
}

var selectedResponses = collection.selectedResponses;

var path = `${options.restPath}`;
var serviceGroups = utils.readDir(path, ignoreInRestRoot);

serviceGroups.forEach(function (serviceGroup) {
var endPoints = utils.readDir(serviceGroup.path);
endPoints.forEach(function (endPoint) {
var services = utils.readDir(endPoint.path);
services.forEach(function (service) {
var name = `${serviceGroup.file}/${endPoint.file}/${service.file}`;
var pathSelectedFile = `${service.path}/mock/response.txt`;

// if nothing is selected remove fiel -> fallback success
if (typeof selectedResponses[name] === 'string') {
utils.writeFile(pathSelectedFile, selectedResponses[name]);
log(`Wrote file "${pathSelectedFile.replace(options.restPath, '')}"`);
} else if (utils.existFile(pathSelectedFile)) {
utils.removeFile(pathSelectedFile);
log(`Removed file "${pathSelectedFile.replace(options.restPath, '')}"`);
}
});
});
});

return true;
}

module.exports = activateCollection;
2 changes: 2 additions & 0 deletions lib/commands/create-defined-directories.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ function checkAndCreateFile(path, contentJson) {
function createDefinedDirectories(options) {

checkAndCreateDirectory(options.restPath);
checkAndCreateDirectory(options.restPath + '/_DTO');
checkAndCreateDirectory(options.restPath + '/_collections');
checkAndCreateFile(options.restPath + '/.validation.json', {});
checkAndCreateFile(options.restPath + '/preferences.json', {});

Expand Down
23 changes: 23 additions & 0 deletions lib/commands/delete-collection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use strict';

var log = require('chip')();
var Utils = require('../Utils');
var utils = new Utils();

function deleteCollection(id, options) {
if (!utils.isFilledString(id)) {
return false;
}

var path = `${options.restPath}/_collections/${id}.json`;

if (!utils.existFile(path)) {
log.error(`cannot delete collection ${id}: file "${path}" don\'t exist!`);
return false;
}

utils.removeFile(path);
return true;
}

module.exports = deleteCollection;
23 changes: 23 additions & 0 deletions lib/commands/get-collection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use strict';

var log = require('chip')();
var Utils = require('../Utils');
var utils = new Utils();

function getCollection(id, options) {

if (!utils.isFilledString(id)) {
return false;
}

var path = `${options.restPath}/_collections/${id}.json`;

if (!utils.existFile(path)) {
log.error(`cannot read collection ${id}: file "${path}" don\'t exist!`);
return false;
}

return JSON.parse(utils.readFile(path));
}

module.exports = getCollection;
Loading

0 comments on commit d69e781

Please sign in to comment.