mongoose-class-wrapper
Version:
Tiny ES6 class-based wrapper for mongoose models.
59 lines (50 loc) • 2.19 kB
JavaScript
;
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; };
function wrap(schema, params) {
var hooks = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var _params$options = params.options,
options = _params$options === undefined ? {} : _params$options,
_params$target = params.target,
target = _params$target === undefined ? params : _params$target;
var proto = target.prototype;
var parent = Object.getPrototypeOf(target);
var staticProps = Object.getOwnPropertyNames(target);
var prototypeProps = Object.getOwnPropertyNames(proto);
var instanceProps = prototypeProps.filter(function (name) {
return name !== 'constructor';
});
// Wrap parent first
if (parent.name) wrap(schema, parent, hooks);
// Add model schema
if (target.schema && _typeof(target.schema) == 'object') {
schema.add(target.schema);
}
// Add middleware hooks
if (target.hooks && _typeof(target.hooks) == 'object') {
for (var hookType in target.hooks) {
for (var hookAction in target.hooks[hookType]) {
var hook = target.hooks[hookType][hookAction];
var index = hooks.indexOf(hook);
if (index < 0) {
hooks.push(hook);
schema[hookType](hookAction, hook);
}
}
}
}
// Add static methods
staticProps.forEach(function (name) {
var method = Object.getOwnPropertyDescriptor(target, name);
if (typeof method.value == 'function') schema.static(name, method.value);
});
// Add methods and virtuals
instanceProps.forEach(function (name) {
var method = Object.getOwnPropertyDescriptor(proto, name);
if (typeof method.value == 'function') schema.method(name, method.value);
if (!options.ignoreGettersAndSetters) {
if (typeof method.get == 'function') schema.virtual(name).get(method.get);
if (typeof method.set == 'function') schema.virtual(name).set(method.set);
}
});
}
module.exports = wrap;