Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

moltyjs

Package Overview
Dependencies
Maintainers
1
Versions
71
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

moltyjs - npm Package Compare versions

Comparing version 0.0.2 to 0.0.3

107

lib/clients/connectionManager.js
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
const MongoDB = require('mongodb');
const MongoDBClient = MongoDB.MongoClient;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
const genericPool = require('generic-pool');
var MongoDB = require('mongodb');
var MongoDBClient = MongoDB.MongoClient;
var genericPool = require('generic-pool');
var defaultOptions = {
const defaultOptions = {
engine: 'mongodb',

@@ -19,29 +15,23 @@ uri: 'mongodb://localhost:27017/test',

var ConnectionManager = function () {
function ConnectionManager(options) {
_classCallCheck(this, ConnectionManager);
class ConnectionManager {
constructor(options) {
options = Object.assign({}, defaultOptions, options);
var uri = options.uri;
const uri = options.uri;
this._pool = genericPool.createPool({
create: function create() {
return new Promise(function (resolve, reject) {
MongoDBClient.connect(uri, {
poolSize: 1,
native_parser: true
}).then(function (client) {
console.log('Connection Manager initialized in: ' + uri);
resolve(client);
});
create: () => new Promise((resolve, reject) => {
MongoDBClient.connect(uri, {
poolSize: 1,
native_parser: true
}).then(client => {
console.log('Connection Manager initialized in: ' + uri);
resolve(client);
});
},
destroy: function destroy(client) {
return new Promise(function (resolve) {
client.close().then(function () {
resolve();
});
}),
destroy: client => new Promise(resolve => {
client.close().then(() => {
resolve();
});
}
})
}, options);

@@ -55,42 +45,29 @@ }

*/
acquire() {
if (!this._pool) throw new Error('You must first connect to the DB before loading/saving documents.');
return this._pool.acquire();
}
_createClass(ConnectionManager, [{
key: 'acquire',
value: function acquire() {
if (!this._pool) throw new Error('You must first connect to the DB before loading/saving documents.');
/**
* acquire(): Release a borrowed resource from the DBClient
*
* @returns {Promise}
*/
release(conn) {
if (!this._pool) throw new Error('You must first connect to the DB before loading/saving documents.');
return this._pool.release(conn);
}
return this._pool.acquire();
}
/**
* Close current client
*
* @returns {Promise}
*/
close() {
if (!this._pool) throw new Error('There is no connection currently active.');
return this._pool.drain();
}
}
/**
* acquire(): Release a borrowed resource from the DBClient
*
* @returns {Promise}
*/
}, {
key: 'release',
value: function release(conn) {
if (!this._pool) throw new Error('You must first connect to the DB before loading/saving documents.');
return this._pool.release(conn);
}
/**
* Close current client
*
* @returns {Promise}
*/
}, {
key: 'close',
value: function close() {
if (!this._pool) throw new Error('There is no connection currently active.');
return this._pool.drain();
}
}]);
return ConnectionManager;
}();
module.exports = ConnectionManager;

@@ -5,24 +5,16 @@ 'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const ConnectionManager = require('./connectionManager');
const ObjectID = require('mongodb').ObjectID;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _require = require('await-to-js');
var ConnectionManager = require('./connectionManager');
var ObjectID = require('mongodb').ObjectID;
const to = _require.to;
var _require = require('await-to-js'),
to = _require.to;
var MongoClient = function () {
function MongoClient() {
_classCallCheck(this, MongoClient);
class MongoClient {
constructor() {
this._connectionManager = null;

@@ -41,660 +33,366 @@ this._models = {};

*/
connect(options) {
if (!this._connectionManager) this._connectionManager = new ConnectionManager(options);
return this;
}
/**
* addModel(): Add model to the MongoClient instance so we know
* all the models side effects needs to take on the DB like
* ensure indexes
*
* @param {Model} model
*/
addModel(model) {
const schema = model._schemaNormalized;
let indexes = [];
Object.keys(schema).forEach(key => {
if ('unique' in schema[key] && schema[key].unique) {
const index = { key: { [key]: 1 }, unique: true, name: key };
indexes.push(index);
}
});
_createClass(MongoClient, [{
key: 'connect',
value: function connect(options) {
if (!this._connectionManager) this._connectionManager = new ConnectionManager(options);
return this;
}
this._models[model._modelName] = {
indexes: indexes
};
/**
* addModel(): Add model to the MongoClient instance so we know
* all the models side effects needs to take on the DB like
* ensure indexes
*
* @param {Model} model
*/
}, {
key: 'addModel',
value: function addModel(model) {
var schema = model._schemaNormalized;
var indexes = [];
Object.keys(schema).forEach(function (key) {
if ('unique' in schema[key] && schema[key].unique) {
var index = { key: _defineProperty({}, key, 1), unique: true, name: key };
indexes.push(index);
}
});
this._models[model._modelName] = {
indexes: indexes
if (model._discriminator) {
this._discriminatorModels[model._discriminator] = {
model,
parent: model._modelName,
discriminatorKey: model._schemaOptions.inheritOptions.discriminatorKey
};
if (model._discriminator) {
this._discriminatorModels[model._discriminator] = {
model: model,
parent: model._modelName,
discriminatorKey: model._schemaOptions.inheritOptions.discriminatorKey
};
} else {
this._models[model._modelName].model = model;
}
} else {
this._models[model._modelName].model = model;
}
}
/**
* _applyDocumentOptions(): Checkf if the document has associtaed
* any options from the schema settings like timestamp or discriminators
*
* @param {Document} doc
* @param {Sting} operation ('insert', 'update')
*/
}, {
key: '_applyDocumentOptions',
value: function _applyDocumentOptions(doc, operation) {
if (doc._options.timestamps && operation === 'insert') {
doc._data['createdAt'] = new Date();
doc._data['updatedAt'] = new Date();
}
if (doc._options.timestamps && operation === 'update') {
doc._data['updatedAt'] = new Date();
}
return doc;
/**
* _applyDocumentOptions(): Checkf if the document has associtaed
* any options from the schema settings like timestamp or discriminators
*
* @param {Document} doc
* @param {Sting} operation ('insert', 'update')
*/
_applyDocumentOptions(doc, operation) {
if (doc._options.timestamps && operation === 'insert') {
doc._data['createdAt'] = new Date();
doc._data['updatedAt'] = new Date();
}
/**
* ObjectId(): Get a unique ObjectId from MongoDB
*
* @returns {ObjectID}
*/
}, {
key: 'ObjectId',
value: function ObjectId() {
return new ObjectID();
if (doc._options.timestamps && operation === 'update') {
doc._data['updatedAt'] = new Date();
}
/**
* isValidObjectId(): Checks if a value is a valid bson ObjectId
*
* @returns {Boolean}
*/
return doc;
}
}, {
key: 'isValidObjectId',
value: function isValidObjectId(id) {
return ObjectID.isValid(id);
}
/**
* ObjectId(): Get a unique ObjectId from MongoDB
*
* @returns {ObjectID}
*/
ObjectId() {
return new ObjectID();
}
/**
* insertOne(): Insert one document into the collection and the
* tenant specifyed. "forceServerObjectId" is set to true in order
* to require server side assign _id
*
* @param {String} tenant
* @param {Document} doc
*
* @returns {Promise}
*/
/**
* isValidObjectId(): Checks if a value is a valid bson ObjectId
*
* @returns {Boolean}
*/
isValidObjectId(id) {
return ObjectID.isValid(id);
}
}, {
key: 'insertOne',
value: function () {
var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(tenant, doc) {
var _this = this;
/**
* insertOne(): Insert one document into the collection and the
* tenant specifyed. "forceServerObjectId" is set to true in order
* to require server side assign _id
*
* @param {String} tenant
* @param {Document} doc
*
* @returns {Promise}
*/
insertOne(tenant, doc) {
var _this = this;
var Document, conn;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(!tenant && typeof tenant != 'string')) {
_context2.next = 2;
break;
}
return _asyncToGenerator(function* () {
if (!tenant && typeof tenant != 'string') throw new Error('Should specify the tenant name (String), got: ' + tenant);
const Document = require('../document');
if (!(doc instanceof Document)) throw new Error('The document should be a proper Document instance');
throw new Error('Should specify the tenant name (String), got: ' + tenant);
// If is a a document that belong to inherit model set
// the discriminator key
if (doc._options.inheritOptions.discriminatorKey) {
doc._data[doc._options.inheritOptions.discriminatorKey] = doc._discriminator ? doc._discriminator : doc._modelName;
}
case 2:
Document = require('../document');
// Ensure index are created
yield _this.createIndexes(tenant, doc._modelName, _this._models[doc._modelName].indexes);
if (doc instanceof Document) {
_context2.next = 5;
break;
}
// Running pre insert hooks
yield doc._preHooks.insert.exec();
throw new Error('The document should be a proper Document instance');
// Acquiring db instance
const conn = yield _this._connectionManager.acquire();
case 5:
return new Promise((() => {
var _ref = _asyncToGenerator(function* (resolve, reject) {
try {
// Check and apply document options before saving
doc = _this._applyDocumentOptions(doc, 'insert');
// If is a a document that belong to inherit model set
// the discriminator key
if (doc._options.inheritOptions.discriminatorKey) {
doc._data[doc._options.inheritOptions.discriminatorKey] = doc._discriminator ? doc._discriminator : doc._modelName;
}
var _ref2 = yield to(conn.db(tenant).collection(doc._modelName).insert(doc._data, { forceServerObjectId: true })),
_ref3 = _slicedToArray(_ref2, 2);
// Ensure index are created
_context2.next = 8;
return this.createIndexes(tenant, doc._modelName, this._models[doc._modelName].indexes);
const error = _ref3[0],
result = _ref3[1];
case 8:
_context2.next = 10;
return doc._preHooks.insert.exec();
case 10:
_context2.next = 12;
return this._connectionManager.acquire();
if (error) {
return reject(error);
} else {
// Running post insert hooks
yield doc._postHooks.insert.exec();
case 12:
conn = _context2.sent;
return _context2.abrupt('return', new Promise(function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(resolve, reject) {
var _ref3, _ref4, error, result;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
// Check and apply document options before saving
doc = _this._applyDocumentOptions(doc, 'insert');
_context.next = 4;
return to(conn.db(tenant).collection(doc._modelName).insert(doc._data, { forceServerObjectId: true }));
case 4:
_ref3 = _context.sent;
_ref4 = _slicedToArray(_ref3, 2);
error = _ref4[0];
result = _ref4[1];
if (!error) {
_context.next = 12;
break;
}
return _context.abrupt('return', reject(error));
case 12:
_context.next = 14;
return doc._postHooks.insert.exec();
case 14:
return _context.abrupt('return', resolve(result));
case 15:
_context.next = 20;
break;
case 17:
_context.prev = 17;
_context.t0 = _context['catch'](0);
reject(_context.t0);
case 20:
_context.prev = 20;
_this._connectionManager.release(conn);
return _context.finish(20);
case 23:
case 'end':
return _context.stop();
}
}
}, _callee, _this, [[0, 17, 20, 23]]);
}));
return function (_x3, _x4) {
return _ref2.apply(this, arguments);
};
}()));
case 14:
case 'end':
return _context2.stop();
return resolve(result);
}
} catch (error) {
reject(error);
} finally {
_this._connectionManager.release(conn);
}
}, _callee2, this);
}));
});
function insertOne(_x, _x2) {
return _ref.apply(this, arguments);
}
return function (_x, _x2) {
return _ref.apply(this, arguments);
};
})());
})();
}
return insertOne;
}()
/**
* findOne(): Fetches the first document that matches the query
* into the collection and the tenant specifyed. "
*
* @param {String} tenant
* @param {Object} query
* @param {Object} options
*
* @returns {Promise}
*/
findOne(tenant, collection, query = {}, options = {}) {
var _this2 = this;
/**
* findOne(): Fetches the first document that matches the query
* into the collection and the tenant specifyed. "
*
* @param {String} tenant
* @param {Object} query
* @param {Object} options
*
* @returns {Promise}
*/
return _asyncToGenerator(function* () {
if (!tenant && typeof tenant != 'string') throw new Error('Should specify the tenant name (String), got: ' + tenant);
if (!collection && typeof collection != 'string') throw new Error('Should specify the collection name (String), got: ' + collection);
}, {
key: 'findOne',
value: function () {
var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(tenant, collection) {
var _this2 = this;
// If we are looking for resources in a discriminator model
// we have to set the proper query and addres to the parent collection
let model = {};
if (_this2._discriminatorModels[collection]) {
if (query[_this2._discriminatorModels[collection].discriminatorKey]) throw new Error('You can not include a specific value for the "discriminatorKey" on the query.');
var query = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var model, conn;
return regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!(!tenant && typeof tenant != 'string')) {
_context4.next = 2;
break;
}
query[_this2._discriminatorModels[collection].discriminatorKey] = collection;
model = _this2._discriminatorModels[collection].model;
collection = _this2._discriminatorModels[collection].parent;
} else {
model = _this2._models[collection].model;
}
throw new Error('Should specify the tenant name (String), got: ' + tenant);
// Ensure index are created
yield _this2.createIndexes(tenant, collection, _this2._models[collection].indexes);
case 2:
if (!(!collection && typeof collection != 'string')) {
_context4.next = 4;
break;
}
// Running pre insert hooks
//await doc._preHooks.insert.exec();
throw new Error('Should specify the collection name (String), got: ' + collection);
// Acquiring db instance
const conn = yield _this2._connectionManager.acquire();
case 4:
return new Promise((() => {
var _ref4 = _asyncToGenerator(function* (resolve, reject) {
try {
// Check and apply document options before saving
//doc = this._applyDocumentOptions(doc, 'insert');
// If we are looking for resources in a discriminator model
// we have to set the proper query and addres to the parent collection
model = {};
var _ref5 = yield to(conn.db(tenant).collection(collection).findOne(query, options)),
_ref6 = _slicedToArray(_ref5, 2);
if (!this._discriminatorModels[collection]) {
_context4.next = 13;
break;
}
const error = _ref6[0],
result = _ref6[1];
if (!query[this._discriminatorModels[collection].discriminatorKey]) {
_context4.next = 8;
break;
}
throw new Error('You can not include a specific value for the "discriminatorKey" on the query.');
if (error) {
return reject(error);
} else {
// Running post insert hooks
//await doc._postHooks.insert.exec();
case 8:
// Binding model properties to the document
const Document = require('../document');
const doc = new Document(result, model._preHooks, model._postHooks, model._methods, model._schemaOptions, model._modelName, model._discriminator);
query[this._discriminatorModels[collection].discriminatorKey] = collection;
model = this._discriminatorModels[collection].model;
collection = this._discriminatorModels[collection].parent;
_context4.next = 14;
break;
case 13:
model = this._models[collection].model;
case 14:
_context4.next = 16;
return this.createIndexes(tenant, collection, this._models[collection].indexes);
case 16:
_context4.next = 18;
return this._connectionManager.acquire();
case 18:
conn = _context4.sent;
return _context4.abrupt('return', new Promise(function () {
var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(resolve, reject) {
var _ref7, _ref8, error, result, Document, doc;
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.prev = 0;
_context3.next = 3;
return to(conn.db(tenant).collection(collection).findOne(query, options));
case 3:
_ref7 = _context3.sent;
_ref8 = _slicedToArray(_ref7, 2);
error = _ref8[0];
result = _ref8[1];
if (!error) {
_context3.next = 11;
break;
}
return _context3.abrupt('return', reject(error));
case 11:
// Running post insert hooks
//await doc._postHooks.insert.exec();
// Binding model properties to the document
Document = require('../document');
doc = new Document(result, model._preHooks, model._postHooks, model._methods, model._schemaOptions, model._modelName, model._discriminator);
return _context3.abrupt('return', resolve(doc));
case 14:
_context3.next = 19;
break;
case 16:
_context3.prev = 16;
_context3.t0 = _context3['catch'](0);
reject(_context3.t0);
case 19:
_context3.prev = 19;
_this2._connectionManager.release(conn);
return _context3.finish(19);
case 22:
case 'end':
return _context3.stop();
}
}
}, _callee3, _this2, [[0, 16, 19, 22]]);
}));
return function (_x9, _x10) {
return _ref6.apply(this, arguments);
};
}()));
case 20:
case 'end':
return _context4.stop();
return resolve(doc);
}
} catch (error) {
reject(error);
} finally {
_this2._connectionManager.release(conn);
}
}, _callee4, this);
}));
});
function findOne(_x5, _x6) {
return _ref5.apply(this, arguments);
}
return function (_x3, _x4) {
return _ref4.apply(this, arguments);
};
})());
})();
}
return findOne;
}()
}, {
key: 'find',
value: function () {
var _ref9 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() {
return regeneratorRuntime.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
throw new Error('Sorry, "find()" method is not supported yet');
case 1:
case 'end':
return _context5.stop();
}
find() {
return _asyncToGenerator(function* () {
// When the connection is available, use it
/*conn.then(async (mongo) => {
limit = limit || 10
page = page || 1
query = query || {}
const skip = page > 0 ? ((page - 1) * limit) : 0
try {
const collection = mongo.db(tenant).collection(coll)
const [error, result] = await to(collection.find(query)
.sort({_id: -1})
.skip(skip)
.limit(limit)
.toArray())
if (error) {
return reject(error)
} else {
return resolve({
cursor: {
currentPage: page,
perPage: limit
},
data: result
})
}
}, _callee5, this);
}));
} catch (error) {
reject(error)
} finally {
// Release the connection after us
ConnectionMgr.release(mongo)
}*/
throw new Error('Sorry, "find()" method is not supported yet');
})();
}
function find() {
return _ref9.apply(this, arguments);
}
/**
* createIndexes(): Creates indexes on the db and collection collection
*
* @param {String} tenant
* @param {String} collection
* @param [{String}] fields
*
* @returns {Promise}
*/
createIndexes(tenant, collection, fields) {
var _this3 = this;
return find;
}()
return _asyncToGenerator(function* () {
if (!tenant && typeof tenant != 'string') throw new Error('Should specify the tenant name (String), got: ' + tenant);
if (!collection && typeof collection != 'string') throw new Error('Should specify the collection name (String), got: ' + collection);
if (!fields && typeof fields != 'object') throw new Error('Should specify the field name (Array), got: ' + fields);
/**
* createIndexes(): Creates indexes on the db and collection collection
*
* @param {String} tenant
* @param {String} collection
* @param [{String}] fields
*
* @returns {Promise}
*/
// Checking if indexes are already set for this tenant and this collection
if (_this3._tenants[tenant] && _this3._tenants[tenant][collection]) return;
}, {
key: 'createIndexes',
value: function () {
var _ref10 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(tenant, collection, fields) {
var _this3 = this;
// Acquiring db instance
const conn = yield _this3._connectionManager.acquire();
var conn;
return regeneratorRuntime.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
if (!(!tenant && typeof tenant != 'string')) {
_context7.next = 2;
break;
}
return new Promise((() => {
var _ref7 = _asyncToGenerator(function* (resolve, reject) {
try {
// Ensure there are no indexes yet
yield to(conn.db(tenant).collection(collection).dropIndexes());
throw new Error('Should specify the tenant name (String), got: ' + tenant);
var _ref8 = yield to(conn.db(tenant).collection(collection).createIndexes(fields)),
_ref9 = _slicedToArray(_ref8, 2);
case 2:
if (!(!collection && typeof collection != 'string')) {
_context7.next = 4;
break;
}
const error = _ref9[0],
result = _ref9[1];
throw new Error('Should specify the collection name (String), got: ' + collection);
case 4:
if (!(!fields && (typeof fields === 'undefined' ? 'undefined' : _typeof(fields)) != 'object')) {
_context7.next = 6;
break;
}
throw new Error('Should specify the field name (Array), got: ' + fields);
case 6:
if (!(this._tenants[tenant] && this._tenants[tenant][collection])) {
_context7.next = 8;
break;
}
return _context7.abrupt('return');
case 8:
_context7.next = 10;
return this._connectionManager.acquire();
case 10:
conn = _context7.sent;
return _context7.abrupt('return', new Promise(function () {
var _ref11 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(resolve, reject) {
var _ref12, _ref13, error, result;
return regeneratorRuntime.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
_context6.prev = 0;
_context6.next = 3;
return to(conn.db(tenant).collection(collection).dropIndexes());
case 3:
_context6.next = 5;
return to(conn.db(tenant).collection(collection).createIndexes(fields));
case 5:
_ref12 = _context6.sent;
_ref13 = _slicedToArray(_ref12, 2);
error = _ref13[0];
result = _ref13[1];
if (!error) {
_context6.next = 13;
break;
}
return _context6.abrupt('return', reject(error));
case 13:
// Set Indexes for this tenant and this collection are already set
_this3._tenants[tenant] = _extends({}, _this3._tenants[tenant], _defineProperty({}, collection, true));
return _context6.abrupt('return', resolve(result));
case 15:
_context6.next = 20;
break;
case 17:
_context6.prev = 17;
_context6.t0 = _context6['catch'](0);
reject(_context6.t0);
case 20:
_context6.prev = 20;
_this3._connectionManager.release(conn);
return _context6.finish(20);
case 23:
case 'end':
return _context6.stop();
}
}
}, _callee6, _this3, [[0, 17, 20, 23]]);
}));
return function (_x14, _x15) {
return _ref11.apply(this, arguments);
};
}()));
case 12:
case 'end':
return _context7.stop();
if (error) {
return reject(error);
} else {
// Set Indexes for this tenant and this collection are already set
_this3._tenants[tenant] = _extends({}, _this3._tenants[tenant], {
[collection]: true
});
return resolve(result);
}
} catch (error) {
reject(error);
} finally {
_this3._connectionManager.release(conn);
}
}, _callee7, this);
}));
});
function createIndexes(_x11, _x12, _x13) {
return _ref10.apply(this, arguments);
}
return function (_x5, _x6) {
return _ref7.apply(this, arguments);
};
})());
})();
}
return createIndexes;
}()
/**
* dropDatabase(): Drop a database, removing it permanently from the server.
*
* @param {String} tenant
* @param {String} collection
* @param [{String}] fields
*
* @returns {Promise}
*/
dropDatabase(tenant) {
var _this4 = this;
/**
* dropDatabase(): Drop a database, removing it permanently from the server.
*
* @param {String} tenant
* @param {String} collection
* @param [{String}] fields
*
* @returns {Promise}
*/
return _asyncToGenerator(function* () {
if (!tenant && typeof tenant != 'string') throw new Error('Should specify the tenant name (String), got: ' + tenant);
}, {
key: 'dropDatabase',
value: function () {
var _ref14 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(tenant) {
var _this4 = this;
// Acquiring db instance
const conn = yield _this4._connectionManager.acquire();
var conn;
return regeneratorRuntime.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
if (!(!tenant && typeof tenant != 'string')) {
_context9.next = 2;
break;
}
return new Promise((() => {
var _ref10 = _asyncToGenerator(function* (resolve, reject) {
try {
var _ref11 = yield to(conn.db(tenant).dropDatabase()),
_ref12 = _slicedToArray(_ref11, 2);
throw new Error('Should specify the tenant name (String), got: ' + tenant);
const error = _ref12[0],
result = _ref12[1];
case 2:
_context9.next = 4;
return this._connectionManager.acquire();
case 4:
conn = _context9.sent;
return _context9.abrupt('return', new Promise(function () {
var _ref15 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(resolve, reject) {
var _ref16, _ref17, error, result;
return regeneratorRuntime.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
_context8.prev = 0;
_context8.next = 3;
return to(conn.db(tenant).dropDatabase());
case 3:
_ref16 = _context8.sent;
_ref17 = _slicedToArray(_ref16, 2);
error = _ref17[0];
result = _ref17[1];
if (!error) {
_context8.next = 11;
break;
}
return _context8.abrupt('return', reject(error));
case 11:
return _context8.abrupt('return', resolve(result));
case 12:
_context8.next = 17;
break;
case 14:
_context8.prev = 14;
_context8.t0 = _context8['catch'](0);
reject(_context8.t0);
case 17:
_context8.prev = 17;
_this4._connectionManager.release(conn);
return _context8.finish(17);
case 20:
case 'end':
return _context8.stop();
}
}
}, _callee8, _this4, [[0, 14, 17, 20]]);
}));
return function (_x17, _x18) {
return _ref15.apply(this, arguments);
};
}()));
case 6:
case 'end':
return _context9.stop();
if (error) {
return reject(error);
} else {
return resolve(result);
}
} catch (error) {
reject(error);
} finally {
_this4._connectionManager.release(conn);
}
}, _callee9, this);
}));
});
function dropDatabase(_x16) {
return _ref14.apply(this, arguments);
}
return function (_x7, _x8) {
return _ref10.apply(this, arguments);
};
})());
})();
}
}
return dropDatabase;
}()
}]);
return MongoClient;
}();
module.exports = new MongoClient();
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
const Middleware = require('./middleware');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
const mongoClient = require('./clients/mongoClient');
var Middleware = require('./middleware');
var mongoClient = require('./clients/mongoClient');
var Document = function () {
function Document(data, preHooks, postHooks, methods, schemaOptions, modelName, discriminator) {
var _this = this;
_classCallCheck(this, Document);
class Document {
constructor(data, preHooks, postHooks, methods, schemaOptions, modelName, discriminator) {
this._data = data;

@@ -31,4 +23,4 @@ //this._methods = methods;

// Applying static methods to the document
Object.keys(methods).forEach(function (key) {
_this[key] = methods[key].bind(_this._data);
Object.keys(methods).forEach(key => {
this[key] = methods[key].bind(this._data);
});

@@ -50,37 +42,28 @@

*/
_applyHooks(hooksList, methods) {
let insertHooks = new Middleware();
let updateHooks = new Middleware();
let deleteHooks = new Middleware();
hooksList.forEach(key => {
switch (key.hook) {
case 'insert':
insertHooks.use(key.fn.bind(this));
break;
case 'update':
updateHooks.use(key.fn.bind(this));
break;
case 'delete':
deleteHooks.use(key.fn.bind(this));
break;
default:
throw new Error('Hook "' + key.hook + '" is not allowed.');
break;
}
});
_createClass(Document, [{
key: '_applyHooks',
value: function _applyHooks(hooksList, methods) {
var _this2 = this;
return { insert: insertHooks, update: updateHooks, delete: deleteHooks };
}
}
var insertHooks = new Middleware();
var updateHooks = new Middleware();
var deleteHooks = new Middleware();
hooksList.forEach(function (key) {
switch (key.hook) {
case 'insert':
insertHooks.use(key.fn.bind(_this2));
break;
case 'update':
updateHooks.use(key.fn.bind(_this2));
break;
case 'delete':
deleteHooks.use(key.fn.bind(_this2));
break;
default:
throw new Error('Hook "' + key.hook + '" is not allowed.');
break;
}
});
return { insert: insertHooks, update: updateHooks, delete: deleteHooks };
}
}]);
return Document;
}();
module.exports = Document;
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
const mongoClient = require('./clients/mongoClient');
const Schema = require('./schema');
const Model = require('./model');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var mongoClient = require('./clients/mongoClient');
var Schema = require('./schema');
var Model = require('./model');
/**
* Molty class
*/
var Molty = function () {
function Molty() {
_classCallCheck(this, Molty);
class Molty {
constructor() {
this.Schema = Schema;

@@ -36,35 +29,25 @@

*/
model(schema, modelName) {
if (this.connection === null) throw new Error('You must first connect to the DB before creating a model.');
if (this.models[modelName]) throw new Error('There is already a model with the same name');
_createClass(Molty, [{
key: 'model',
value: function model(schema, modelName) {
if (this.connection === null) throw new Error('You must first connect to the DB before creating a model.');
this.models[modelName] = new Model(schema, modelName);
if (this.models[modelName]) throw new Error('There is already a model with the same name');
return this.models[modelName];
}
this.models[modelName] = new Model(schema, modelName);
/**
* connect(): Connect to a database through the DBClient
*
* @param {Object} options
*
* @returns {Promise}
*/
connect(options) {
if (!this.connection) this.connection = mongoClient.connect(options);
return this.connection;
}
}
return this.models[modelName];
}
/**
* connect(): Connect to a database through the DBClient
*
* @param {Object} options
*
* @returns {Promise}
*/
}, {
key: 'connect',
value: function connect(options) {
if (!this.connection) this.connection = mongoClient.connect(options);
return this.connection;
}
}]);
return Molty;
}();
module.exports = exports = new Molty();
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
//- A Promise-based middleware implementation
var nextTick = 'undefined' !== typeof process ? process.nextTick : 'undefined' !== typeof setImmediate ? setImmediate : setTimeout;
let nextTick = 'undefined' !== typeof process ? process.nextTick : 'undefined' !== typeof setImmediate ? setImmediate : setTimeout;
var Middleware = function () {
class Middleware {
/** create a new Middleware */
function Middleware() {
_classCallCheck(this, Middleware);
constructor() {
this.middlewares = [];

@@ -20,60 +14,34 @@ }

/** add a function to middleware stack */
_createClass(Middleware, [{
key: 'use',
value: function use(fn) {
if (!fn || typeof fn !== 'function') {
throw new TypeError("Argument to use must be of type 'Function'");
}
this.middlewares.push(fn);
use(fn) {
if (!fn || typeof fn !== 'function') {
throw new TypeError("Argument to use must be of type 'Function'");
}
/** execute the middlewares */
this.middlewares.push(fn);
}
}, {
key: 'exec',
value: function exec() {
var _this = this;
/** execute the middlewares */
exec(...args) {
return new Promise((resolve, reject) => {
// check for early exit
if (!this.middlewares.length) return resolve(...args);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return new Promise(function (resolve, reject) {
// check for early exit
if (!_this.middlewares.length) return resolve.apply(undefined, args);
// kickstart the chain
var _execute = function _execute(i) {
for (var _len2 = arguments.length, args0 = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args0[_key2 - 1] = arguments[_key2];
// kickstart the chain
let _execute = (i, ...args0) => {
nextTick(() => {
try {
this.middlewares[i]((...returnValue) => {
if (returnValue.length && returnValue[0] instanceof Error) return reject(returnValue[0]);else if (i >= this.middlewares.length - 1) return resolve(...returnValue);else return _execute(i + 1, ...returnValue);
}, ...args0);
} catch (err) {
reject(err);
}
}, 1);
};
nextTick(function () {
try {
var _middlewares;
_execute(0, ...args);
});
}
}
(_middlewares = _this.middlewares)[i].apply(_middlewares, [function () {
for (var _len3 = arguments.length, returnValue = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
returnValue[_key3] = arguments[_key3];
}
if (returnValue.length && returnValue[0] instanceof Error) return reject(returnValue[0]);else if (i >= _this.middlewares.length - 1) return resolve.apply(undefined, returnValue);else return _execute.apply(undefined, [i + 1].concat(returnValue));
}].concat(args0));
} catch (err) {
reject(err);
}
}, 1);
};
_execute.apply(undefined, [0].concat(args));
});
}
}]);
return Middleware;
}();
module.exports = Middleware;
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
const mongoClient = require('./clients/mongoClient');
const Document = require('./document');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _require = require('./validators');
var mongoClient = require('./clients/mongoClient');
var Document = require('./document');
const isValidType = _require.isValidType,
isObject = _require.isObject,
isEmptyValue = _require.isEmptyValue,
isString = _require.isString,
isInEnum = _require.isInEnum,
isNumber = _require.isNumber;
var _require = require('./validators'),
isValidType = _require.isValidType,
isObject = _require.isObject,
isEmptyValue = _require.isEmptyValue,
isString = _require.isString,
isInEnum = _require.isInEnum,
isNumber = _require.isNumber;
var Model = function () {
class Model {
/**

@@ -27,5 +25,3 @@ * Model(): Model conmstructor

*/
function Model(schema, modelName, discriminator) {
_classCallCheck(this, Model);
constructor(schema, modelName, discriminator) {
if (arguments.length < 1) throw new Error('Schema is missing');

@@ -60,232 +56,200 @@

*/
_validateStaticMethodsName(methods, schema) {
Object.keys(methods).forEach(key => {
if (key === '_preHooks' || key === '_postHooks' || key === '_data') throw new Error('Static methods can not be called like: ' + key);
if (key in schema) throw new Error('Static methods can not be called like an schema field name: ' + key);
_createClass(Model, [{
key: '_validateStaticMethodsName',
value: function _validateStaticMethodsName(methods, schema) {
var _this = this;
// Objects nested
if (schema[key] && !schema[key].type && isObject(schema[key])) {
return this._validateStaticMethodsName(methods, schema[key]);
}
});
}
Object.keys(methods).forEach(function (key) {
if (key === '_preHooks' || key === '_postHooks' || key === '_data') throw new Error('Static methods can not be called like: ' + key);
/**
* _validateDiscriminatorName(): Check if there is a schema field
* with the same name as the discriminator key
*
* @param {Object} discriminator
* @params {Object} schema
*/
_validateDiscriminatorName(discriminator, schema) {
Object.keys(schema).forEach(key => {
if (key === '_preHooks' || key === '_postHooks' || key === '_data') throw new Error('Discriminator name can not be called like this: ' + key);
if (key in schema) throw new Error('Static methods can not be called like an schema field name: ' + key);
if (key === discriminator) throw new Error('Discriminator name can not be called like anothe schema field: ' + key);
// Objects nested
if (schema[key] && !schema[key].type && isObject(schema[key])) {
return _this._validateStaticMethodsName(methods, schema[key]);
}
});
}
// Objects nested
if (!schema[key].type && isObject(schema[key])) {
return this._validateDiscriminatorName(discriminator, schema[key]);
}
});
}
/**
* _validateDiscriminatorName(): Check if there is a schema field
* with the same name as the discriminator key
*
* @param {Object} discriminator
* @params {Object} schema
*/
/**
* new(): Create a new document based on this model
*
* @param {Object} payload
*
* @returns {Onject} doc
*/
new(payload) {
// Check if paylaod field names are correct
this._validatePayloadFieldNames(payload, this._schemaNormalized);
// Normalize the payload with the model schema
let data = this._normalizePayload(payload, this._schemaNormalized);
}, {
key: '_validateDiscriminatorName',
value: function _validateDiscriminatorName(discriminator, schema) {
var _this2 = this;
// Returning the new document created
return new Document(data, this._preHooks, this._postHooks, this._methods, this._schemaOptions, this._modelName, this._discriminator);
}
Object.keys(schema).forEach(function (key) {
if (key === '_preHooks' || key === '_postHooks' || key === '_data') throw new Error('Discriminator name can not be called like this: ' + key);
/**
* discriminator(): Create a new discriminator for an schema
* which inherit all the properties from the parent schema
*
* @param {Schema} schemaDiscriminator
* @param {String} discriminatorModelName
*/
discriminator(schemaDiscriminator, discriminatorModelName) {
var _schemaDiscriminator$ = schemaDiscriminator._options.inheritOptions;
const merge = _schemaDiscriminator$.merge,
childDiscriminatorKey = _schemaDiscriminator$.discriminatorKey;
if (key === discriminator) throw new Error('Discriminator name can not be called like anothe schema field: ' + key);
// Objects nested
if (!schema[key].type && isObject(schema[key])) {
return _this2._validateDiscriminatorName(discriminator, schema[key]);
}
});
}
if (!childDiscriminatorKey) throw new Error('To create an inherited model you have to sepcify the "discriminatorKey" in the schema "options" field.');
/**
* new(): Create a new document based on this model
*
* @param {Object} payload
*
* @returns {Onject} doc
*/
const parentDiscriminatorKey = this._schemaOptions.inheritOptions.discriminatorKey;
}, {
key: 'new',
value: function _new(payload) {
// Check if paylaod field names are correct
this._validatePayloadFieldNames(payload, this._schemaNormalized);
// Normalize the payload with the model schema
var data = this._normalizePayload(payload, this._schemaNormalized);
// Returning the new document created
return new Document(data, this._preHooks, this._postHooks, this._methods, this._schemaOptions, this._modelName, this._discriminator);
}
if (!parentDiscriminatorKey) throw new Error('You can not inherit from this model, you should add the "discriminatorKey" option in both schemas.');
/**
* discriminator(): Create a new discriminator for an schema
* which inherit all the properties from the parent schema
*
* @param {Schema} schemaDiscriminator
* @param {String} discriminatorModelName
*/
if (parentDiscriminatorKey !== childDiscriminatorKey) throw new Error('The "discriminatorKey" from the parent and the child model shoul be the same: [' + parentDiscriminatorKey + ',' + childDiscriminatorKey + ']');
}, {
key: 'discriminator',
value: function discriminator(schemaDiscriminator, discriminatorModelName) {
var _this3 = this;
let schema = {
methods: {},
_preHooks: {},
_postHooks: {},
_schema: {},
_options: {}
};
var _schemaDiscriminator$ = schemaDiscriminator._options.inheritOptions,
merge = _schemaDiscriminator$.merge,
childDiscriminatorKey = _schemaDiscriminator$.discriminatorKey;
schema._options = schemaDiscriminator._options;
if (merge && merge.indexOf('methods') >= 0) {
Object.keys(schemaDiscriminator.methods).forEach(key => {
if (key in this._methods) throw new Error('Static methods from a child schema can not be called like another method from the parent: ' + key);
});
if (!childDiscriminatorKey) throw new Error('To create an inherited model you have to sepcify the "discriminatorKey" in the schema "options" field.');
schema.methods = Object.assign({}, this._methods, schemaDiscriminator.methods);
}
var parentDiscriminatorKey = this._schemaOptions.inheritOptions.discriminatorKey;
if (merge && merge.indexOf('preHooks') >= 0) {
schema._preHooks = this._preHooks.concat(schemaDiscriminator._preHooks);
}
if (merge && merge.indexOf('postHooks') >= 0) {
schema._postHooks = this._postHooks.concat(schemaDiscriminator._postHooks);
}
schema._schema = Object.assign({}, this._schemaNormalized, schemaDiscriminator._schema);
if (!parentDiscriminatorKey) throw new Error('You can not inherit from this model, you should add the "discriminatorKey" option in both schemas.');
this._validateDiscriminatorName(childDiscriminatorKey, schema._schema);
if (parentDiscriminatorKey !== childDiscriminatorKey) throw new Error('The "discriminatorKey" from the parent and the child model shoul be the same: [' + parentDiscriminatorKey + ',' + childDiscriminatorKey + ']');
const discriminatorModel = new Model(schema, this._modelName, discriminatorModelName);
var schema = {
methods: {},
_preHooks: {},
_postHooks: {},
_schema: {},
_options: {}
};
if (this._childsModels[discriminatorModelName]) throw new Error('There is already model discriminator with the same name: ' + discriminatorModelName);
schema._options = schemaDiscriminator._options;
this._childsModels[discriminatorModelName] = discriminatorModel;
if (merge && merge.indexOf('methods') >= 0) {
Object.keys(schemaDiscriminator.methods).forEach(function (key) {
if (key in _this3._methods) throw new Error('Static methods from a child schema can not be called like another method from the parent: ' + key);
});
return discriminatorModel;
}
schema.methods = Object.assign({}, this._methods, schemaDiscriminator.methods);
/**
* _validatePayloadFieldNames(): Check if all the field names
* from the payload corresponds to schema with.
*
* @param {Object} payload
* @param {schema} schema
*/
_validatePayloadFieldNames(payload, schema) {
Object.keys(payload).forEach(key => {
if (schema[key] === undefined && key !== '_id') {
throw new Error('Field name ' + key + ' does not correspond to any field name on the schema');
}
if (merge && merge.indexOf('preHooks') >= 0) {
schema._preHooks = this._preHooks.concat(schemaDiscriminator._preHooks);
// Objects nested
if (!schema[key].type && isObject(schema[key])) {
return this._validatePayloadFieldNames(payload[key], schema[key]);
}
if (merge && merge.indexOf('postHooks') >= 0) {
schema._postHooks = this._postHooks.concat(schemaDiscriminator._postHooks);
});
}
/**
* _normalizePayload(): Assign default values to the payload
* and check if the data type and format is accepted by the schema
* assigned to this model
*
* @param {Object} payload
* @param {schema} schema
*
* returns {Object} doc
*/
_normalizePayload(payload, schema) {
Object.keys(schema).forEach(key => {
// Default values
if (payload[key] === undefined && 'default' in schema[key]) {
const defaultValue = schema[key].default;
payload[key] = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
return;
}
schema._schema = Object.assign({}, this._schemaNormalized, schemaDiscriminator._schema);
// No required values
if (payload[key] === undefined && !schema[key].required) return;
this._validateDiscriminatorName(childDiscriminatorKey, schema._schema);
// Objects nested
if (!schema[key].type && isObject(payload[key])) {
payload[key] = this._normalizePayload(payload[key], schema[key]);
return;
}
var discriminatorModel = new Model(schema, this._modelName, discriminatorModelName);
// Is required validation
if (schema[key].required && isEmptyValue(payload[key])) {
throw new Error('Key ' + key + ' is required' + ', but got ' + payload[key]);
}
if (this._childsModels[discriminatorModelName]) throw new Error('There is already model discriminator with the same name: ' + discriminatorModelName);
// Validation type
if (!isValidType(payload[key], schema[key].type)) {
throw new Error('Unsuported value (' + payload[key] + ') for type ' + schema[key].type);
}
this._childsModels[discriminatorModelName] = discriminatorModel;
// Reg exp validation
if (schema[key].match && isString(payload[key]) && !schema[key].match.test(payload[key])) {
throw new Error('Value assigned to ' + key + ' does not match the regex/string ' + schema[key].match.toString() + '. Value was ' + payload[key]);
}
return discriminatorModel;
}
// Enum validation
if (!isInEnum(schema[key].enum, payload[key])) {
throw new Error('Value assigned to ' + key + ' should be in enum [' + schema[key].enum.join(', ') + '], got ' + payload[key]);
}
/**
* _validatePayloadFieldNames(): Check if all the field names
* from the payload corresponds to schema with.
*
* @param {Object} payload
* @param {schema} schema
*/
// Min value validation
if (isNumber(schema[key].min) && payload[key] < schema[key].min) {
throw new Error('Value assigned to ' + key + ' is less than min, ' + schema[key].min + ', got ' + payload[key]);
}
}, {
key: '_validatePayloadFieldNames',
value: function _validatePayloadFieldNames(payload, schema) {
var _this4 = this;
// Max value validation
if (isNumber(schema[key].max) && payload[key] > schema[key].max) {
throw new Error('Value assigned to ' + key + ' is less than max, ' + schema[key].max + ', got ' + payload[key]);
}
Object.keys(payload).forEach(function (key) {
if (schema[key] === undefined && key !== '_id') {
throw new Error('Field name ' + key + ' does not correspond to any field name on the schema');
}
// Custom validation
if (typeof schema[key].validate === 'function' && !schema[key].validate(payload[key])) {
throw new Error('Value assigned to ' + key + ' failed custom validator. Value was ' + payload[key]);
}
});
// Objects nested
if (!schema[key].type && isObject(schema[key])) {
return _this4._validatePayloadFieldNames(payload[key], schema[key]);
}
});
}
return payload;
}
}
/**
* _normalizePayload(): Assign default values to the payload
* and check if the data type and format is accepted by the schema
* assigned to this model
*
* @param {Object} payload
* @param {schema} schema
*
* returns {Object} doc
*/
}, {
key: '_normalizePayload',
value: function _normalizePayload(payload, schema) {
var _this5 = this;
Object.keys(schema).forEach(function (key) {
// Default values
if (payload[key] === undefined && 'default' in schema[key]) {
var defaultValue = schema[key].default;
payload[key] = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
return;
}
// No required values
if (payload[key] === undefined && !schema[key].required) return;
// Objects nested
if (!schema[key].type && isObject(payload[key])) {
payload[key] = _this5._normalizePayload(payload[key], schema[key]);
return;
}
// Is required validation
if (schema[key].required && isEmptyValue(payload[key])) {
throw new Error('Key ' + key + ' is required' + ', but got ' + payload[key]);
}
// Validation type
if (!isValidType(payload[key], schema[key].type)) {
throw new Error('Unsuported value (' + payload[key] + ') for type ' + schema[key].type);
}
// Reg exp validation
if (schema[key].match && isString(payload[key]) && !schema[key].match.test(payload[key])) {
throw new Error('Value assigned to ' + key + ' does not match the regex/string ' + schema[key].match.toString() + '. Value was ' + payload[key]);
}
// Enum validation
if (!isInEnum(schema[key].enum, payload[key])) {
throw new Error('Value assigned to ' + key + ' should be in enum [' + schema[key].enum.join(', ') + '], got ' + payload[key]);
}
// Min value validation
if (isNumber(schema[key].min) && payload[key] < schema[key].min) {
throw new Error('Value assigned to ' + key + ' is less than min, ' + schema[key].min + ', got ' + payload[key]);
}
// Max value validation
if (isNumber(schema[key].max) && payload[key] > schema[key].max) {
throw new Error('Value assigned to ' + key + ' is less than max, ' + schema[key].max + ', got ' + payload[key]);
}
// Custom validation
if (typeof schema[key].validate === 'function' && !schema[key].validate(payload[key])) {
throw new Error('Value assigned to ' + key + ' failed custom validator. Value was ' + payload[key]);
}
});
return payload;
}
}]);
return Model;
}();
module.exports = Model;
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
const utils = require('./utils');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _require = require('./validators');
var utils = require('./utils');
const isSupportedType = _require.isSupportedType,
isArray = _require.isArray,
isObject = _require.isObject;
var _require = require('./validators'),
isSupportedType = _require.isSupportedType,
isArray = _require.isArray,
isObject = _require.isObject;
var Schema = function () {
class Schema {
/**

@@ -23,5 +21,3 @@ * Schema(): Schema constructor

*/
function Schema(schema, options) {
_classCallCheck(this, Schema);
constructor(schema, options) {
if (arguments.length < 1) throw new Error('Schema is missing');

@@ -47,71 +43,55 @@

*/
_createClass(Schema, [{
key: '_isValidFormatType',
value: function _isValidFormatType(schema) {
Object.keys(schema).forEach(function (key) {
if (schema[key].type) {
if (!isSupportedType(schema[key].type)) {
throw new Error('Unsupported type or bad variable: ' + key);
}
} else {
if (Object.keys(schema[key]).length <= 0) {
throw new Error('Unsupported type or bad variable: ' + key);
}
_isValidFormatType(schema) {
Object.keys(schema).forEach(key => {
if (schema[key].type) {
if (!isSupportedType(schema[key].type)) {
throw new Error('Unsupported type or bad variable: ' + key);
}
});
}
} else {
if (Object.keys(schema[key]).length <= 0) {
throw new Error('Unsupported type or bad variable: ' + key);
}
}
});
}
/**
* pre(): Bind pre hook functions to the Schema
*
* @param {String} hook=['validate', 'save', 'update', 'delete']
* @param {Function} cb hook function
*/
/**
* pre(): Bind pre hook functions to the Schema
*
* @param {String} hook=['validate', 'save', 'update', 'delete']
* @param {Function} cb hook function
*/
pre(hook, fn) {
if (arguments.length < 2) throw new Error('Hooks params are missing');
if (!this._isValidHook(hook)) throw new Error('Hook "' + hook + '" is not allowed.');
}, {
key: 'pre',
value: function pre(hook, fn) {
if (arguments.length < 2) throw new Error('Hooks params are missing');
if (!this._isValidHook(hook)) throw new Error('Hook "' + hook + '" is not allowed.');
this._preHooks.push({ hook, fn });
}
this._preHooks.push({ hook: hook, fn: fn });
}
/**
* post(): Bind post hook functions to the Schema
*
* @param {String} hook=['validate', 'save', 'update', 'delete']
* @param {Function} fn hook function
*/
post(hook, fn) {
if (arguments.length < 2) throw new Error('Hooks params are missing');
if (!this._isValidHook(hook)) throw new Error('Hook "' + hook + '" is not allowed.');
/**
* post(): Bind post hook functions to the Schema
*
* @param {String} hook=['validate', 'save', 'update', 'delete']
* @param {Function} fn hook function
*/
this._postHooks.push({ hook, fn });
}
}, {
key: 'post',
value: function post(hook, fn) {
if (arguments.length < 2) throw new Error('Hooks params are missing');
if (!this._isValidHook(hook)) throw new Error('Hook "' + hook + '" is not allowed.');
/**
* _isValidHook(): Check is the hook is allowed or not
*
* @param {String} hook Hook name
*
* @returns {Boolean}
*/
_isValidHook(hook) {
const validHooks = ['validate', 'insert', 'update', 'delete'];
return validHooks.indexOf(hook) > -1;
}
}
this._postHooks.push({ hook: hook, fn: fn });
}
/**
* _isValidHook(): Check is the hook is allowed or not
*
* @param {String} hook Hook name
*
* @returns {Boolean}
*/
}, {
key: '_isValidHook',
value: function _isValidHook(hook) {
var validHooks = ['validate', 'insert', 'update', 'delete'];
return validHooks.indexOf(hook) > -1;
}
}]);
return Schema;
}();
module.exports = Schema;
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
const _ = require('lodash');
const DB = {}; //require('./clients').getClient;
var _ = require('lodash');
var DB = {}; //require('./clients').getClient;
var isString = function isString(s) {
const isString = function isString(s) {
return _.isString(s);
};
var isNumber = function isNumber(n) {
const isNumber = function isNumber(n) {
return _.isNumber(n) && _.isFinite(n) && !isString(n);
};
var isBoolean = function isBoolean(b) {
const isBoolean = function isBoolean(b) {
return _.isBoolean(b);
};
var isDate = function isDate(d) {
const isDate = function isDate(d) {
return isNumber(d) || _.isDate(d) || isNumber(Date.parse(d));
};
var isBuffer = function isBuffer(b) {
return (typeof b === 'undefined' ? 'undefined' : _typeof(b)) === 'object' || b instanceof Buffer;
const isBuffer = function isBuffer(b) {
return typeof b === 'object' || b instanceof Buffer;
};
var isObject = function isObject(o) {
const isObject = function isObject(o) {
return _.isObject(o);
};
var isArray = function isArray(a) {
const isArray = function isArray(a) {
return _.isArray(a);
};
var isDocument = function isDocument(m) {
const isDocument = function isDocument(m) {
return m && m.documentClass && m.documentClass() === 'document';
};
var isEmbeddedDocument = function isEmbeddedDocument(e) {
const isEmbeddedDocument = function isEmbeddedDocument(e) {
return e && e.documentClass && e.documentClass() === 'embedded';
};
var isReferenceable = function isReferenceable(r) {
const isReferenceable = function isReferenceable(r) {
return isDocument(r) || isNativeId(r);
};
var isNativeId = function isNativeId(n) {
const isNativeId = function isNativeId(n) {
return DB().isNativeId(n);
};
var isSupportedType = function isSupportedType(t) {
const isSupportedType = function isSupportedType(t) {
return t === String || t === Number || t === Boolean || t === Buffer || t === Date || t === Array || isArray(t) || t === Object || t instanceof Object || typeof t.documentClass === 'function';
};
var isType = function isType(value, type) {
const isType = function isType(value, type) {
if (type === String) {

@@ -82,3 +80,3 @@ return isString(value);

var isValidType = function isValidType(value, type) {
const isValidType = function isValidType(value, type) {
// NOTE

@@ -105,5 +103,5 @@ // Maybe look at this:

if (isArray(type) && type.length === 1 && isArray(value)) {
var arrayType = type[0];
for (var i = 0; i < value.length; i++) {
var v = value[i];
let arrayType = type[0];
for (let i = 0; i < value.length; i++) {
let v = value[i];
if (!isType(v, arrayType)) {

@@ -125,3 +123,3 @@ return false;

var isInEnum = function isInEnum(choices, choice) {
const isInEnum = function isInEnum(choices, choice) {
if (!choices) {

@@ -133,3 +131,3 @@ return true;

var isEmptyValue = function isEmptyValue(value) {
const isEmptyValue = function isEmptyValue(value) {
return typeof value === 'undefined' || !(typeof value === 'number' || value instanceof Date || typeof value === 'boolean') && 0 === Object.keys(value).length;

@@ -136,0 +134,0 @@ };

{
"name": "moltyjs",
"version": "0.0.2",
"version": "0.0.3",
"description": "A tiny ODM for MongoDB with multy tenancy support.",

@@ -5,0 +5,0 @@ "main": "lib/index.js",

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc