Skip to content

Commit

Permalink
Splitted internal methods into helper modules
Browse files Browse the repository at this point in the history
  • Loading branch information
Nataniel López committed Jan 14, 2020
1 parent b0bf0d8 commit 5632bef
Show file tree
Hide file tree
Showing 15 changed files with 327 additions and 244 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Changed
- Splitted internal methods into helper modules

### Fixed
- MongoDB driver compatibility by using a Model instance

Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

'use strict';

const logger = require('./lib/utils/colorful-lllog')();
const logger = require('./lib/colorful-lllog')();

const MongodbIndexCreator = require('./lib/mongodb-index-creator');

Expand Down
File renamed without changes.
38 changes: 38 additions & 0 deletions lib/helpers/collections.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'use strict';

const { struct } = require('superstruct');

const isObject = require('./is-object');

const MongodbIndexCreatorError = require('../mongodb-index-creator-error');

const collectionStruct = struct([
{
name: 'string',
key: 'object',
unique: 'boolean?'
}
]);

class CollectionsHelper {

static validate(collections) {

if(!isObject(collections)) {
throw new MongodbIndexCreatorError('Invalid collections: Should exist and must be an object, also not an array.',
MongodbIndexCreatorError.codes.INVALID_COLLECTIONS);
}

try {

Object.values(collections).forEach(collection => collectionStruct(collection));

} catch(err) {

throw new MongodbIndexCreatorError(`Invalid collection index: ${err.message}`,
MongodbIndexCreatorError.codes.INVALID_COLLECTION_INDEXES);
}
}
}

module.exports = CollectionsHelper;
80 changes: 80 additions & 0 deletions lib/helpers/indexes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
'use strict';

const Model = require('./model');
const isObject = require('./is-object');
const Collections = require('./collections');

const MongodbIndexCreatorError = require('../mongodb-index-creator-error');

const DEFAULT_ID_INDEX_NAME = '_id_';

class IndexesHelper {

/**
* Generate fake models for the received collections using the specified method
* @param {Function} modelMethod The Model method that will generate the instance, may be different for core or client models
* @param {Any} methodParam The param for the specified method
* @param {Object.<array>} collections The collections
* @returns {Array.<object>} An array of objects with the Model instance for each collection with the indexes
*/
static _generateModels(modelMethod, methodParam, collections) {

return Object.entries(collections).map(([collection, indexes]) => (
{
modelInstance: Model[modelMethod](methodParam, collection),
indexes
}
));
}

static getIndexesDifference(indexesA, indexesB) {
return indexesA.filter(indexA => !indexesB.some(({ name }) => indexA.name === name));
}

static async get(modelInstance) {

const indexes = await modelInstance.getIndexes();

return indexes.filter(({ name }) => name !== DEFAULT_ID_INDEX_NAME);
}

static prepareCoreIndexes(coreSchemas) {

if(!isObject(coreSchemas)) {
throw new MongodbIndexCreatorError('Invalid core schemas: Should exist and must be an object.',
MongodbIndexCreatorError.codes.INVALID_CORE_SCHEMAS);
}

return Object.entries(coreSchemas).reduce((prev, [databaseKey, collections]) => {

Collections.validate(collections);

return [
...prev,
...this._generateModels('getInstanceByDatabaseKey', databaseKey, collections)
];

}, []);
}

static prepareClientIndexes(clients, clientSchemas) {

if(!isObject(clientSchemas)) {
throw new MongodbIndexCreatorError('Invalid client schemas: Should exist and must be an object.',
MongodbIndexCreatorError.codes.INVALID_CLIENT_SCHEMAS);
}

Collections.validate(clientSchemas);

return clients.reduce((prev, client) => {

return [
...prev,
...this._generateModels('getSessionInstance', client, clientSchemas)
];

}, []);
}
}

module.exports = IndexesHelper;
12 changes: 12 additions & 0 deletions lib/helpers/is-object.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict';

/**
* Validates if the received item is an object and not an array
* @param {Object} object the object
* @returns {Boolean} true if is valid, false otherwise
*/
function isObject(object) {
return object !== null && typeof object === 'object' && !Array.isArray(object);
}

module.exports = isObject;
14 changes: 1 addition & 13 deletions lib/utils/utils.js → lib/helpers/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,6 @@

const Model = require('@janiscommerce/model');

/**
* Validates if the received item is an object and not an array
* @param {Object} object the object
* @returns {Boolean} true if is valid, false otherwise
*/
function isObject(object) {
return object !== null && typeof object === 'object' && !Array.isArray(object);
}

class ModelGenerator {

static getInstanceByDatabaseKey(databaseKey, table) {
Expand Down Expand Up @@ -48,7 +39,4 @@ class ModelGenerator {
}
}

module.exports = {
isObject,
ModelGenerator
};
module.exports = ModelGenerator;
26 changes: 26 additions & 0 deletions lib/helpers/results.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';

class ResultsHelper {

/**
* Save the results of the specified type, if the type already have a value it will be joined
* @param {String} type The result type, such as: created, failed, etc...
* @param {Number} result The result values to save
*/
static save(type, result) {

if(!this.results)
this.results = {};

if(this.results[type])
this.results[type] += result;
else
this.results[type] = result;
}

static export() {
return `Changes summary:\n${JSON.stringify(this.results, null, 2)}`;
}
}

module.exports = ResultsHelper;
36 changes: 36 additions & 0 deletions lib/helpers/schemas.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

const path = require('path');

const DEFAULT_SCHEMAS_PATH = path.join(process.cwd(), 'schemas', 'mongo');

class SchemasHelper {

constructor(schemasPath) {
this.schemasPath = schemasPath || DEFAULT_SCHEMAS_PATH;
}

get core() {

try {

return require(path.join(this.schemasPath, 'core')); // eslint-disable-line global-require, import/no-dynamic-require

} catch(err) {
return undefined;
}
}

get client() {

try {

return require(path.join(this.schemasPath, 'clients')); // eslint-disable-line global-require, import/no-dynamic-require

} catch(err) {
return undefined;
}
}
}

module.exports = SchemasHelper;
Loading

0 comments on commit 5632bef

Please sign in to comment.