applyMethods.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. /*!
  3. * Register methods for this model
  4. *
  5. * @param {Model} model
  6. * @param {Schema} schema
  7. */
  8. module.exports = function applyMethods(model, schema) {
  9. function apply(method, schema) {
  10. Object.defineProperty(model.prototype, method, {
  11. get: function() {
  12. var h = {};
  13. for (var k in schema.methods[method]) {
  14. h[k] = schema.methods[method][k].bind(this);
  15. }
  16. return h;
  17. },
  18. configurable: true
  19. });
  20. }
  21. for (var method in schema.methods) {
  22. if (schema.tree.hasOwnProperty(method)) {
  23. throw new Error('You have a method and a property in your schema both ' +
  24. 'named "' + method + '"');
  25. }
  26. if (typeof schema.methods[method] === 'function') {
  27. model.prototype[method] = schema.methods[method];
  28. } else {
  29. apply(method, schema);
  30. }
  31. }
  32. // Recursively call `applyMethods()` on child schemas
  33. model.$appliedMethods = true;
  34. for (var i = 0; i < schema.childSchemas.length; ++i) {
  35. if (schema.childSchemas[i].model.$appliedMethods) {
  36. continue;
  37. }
  38. applyMethods(schema.childSchemas[i].model, schema.childSchemas[i].schema);
  39. }
  40. };