You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.7 KiB

  1. var Query = require('./query');
  2. function NamedScope () {}
  3. NamedScope.prototype.query;
  4. NamedScope.prototype.where = function () {
  5. var q = this.query || (this.query = new Query());
  6. q.where.apply(q, arguments);
  7. return q;
  8. };
  9. /**
  10. * Decorate
  11. *
  12. * @param {NamedScope} target
  13. * @param {Object} getters
  14. * @api private
  15. */
  16. NamedScope.prototype.decorate = function (target, getters) {
  17. var name = this.name
  18. , block = this.block
  19. , query = this.query;
  20. if (block) {
  21. if (block.length === 0) {
  22. Object.defineProperty(target, name, {
  23. get: getters.block0(block)
  24. });
  25. } else {
  26. target[name] = getters.blockN(block);
  27. }
  28. } else {
  29. Object.defineProperty(target, name, {
  30. get: getters.basic(query)
  31. });
  32. }
  33. };
  34. NamedScope.prototype.compile = function (model) {
  35. var allScopes = this.scopesByName
  36. , scope;
  37. for (var k in allScopes) {
  38. scope = allScopes[k];
  39. scope.decorate(model, {
  40. block0: function (block) {
  41. return function () {
  42. var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
  43. block.call(cquery);
  44. return this;
  45. };
  46. },
  47. blockN: function (block) {
  48. return function () {
  49. var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
  50. block.apply(cquery, arguments);
  51. return this;
  52. };
  53. },
  54. basic: function (query) {
  55. return function () {
  56. var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
  57. cquery.find(query);
  58. return this;
  59. };
  60. }
  61. });
  62. }
  63. };
  64. module.exports = NamedScope;