* Apply a scope created in `define` to the model. * * @example how to create scopes * const Model = sequelize.define('model', attributes, { * defaultScope: { * where: { * username: 'dan' * }, * limit: 12 * }, * scopes: { *
(option)
| 1580 | * @returns {Model} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope. |
| 1581 | */ |
| 1582 | static scope(option) { |
| 1583 | const self = class extends this {}; |
| 1584 | let scope; |
| 1585 | let scopeName; |
| 1586 | |
| 1587 | Object.defineProperty(self, 'name', { value: this.name }); |
| 1588 | |
| 1589 | self._scope = {}; |
| 1590 | self._scopeNames = []; |
| 1591 | self.scoped = true; |
| 1592 | |
| 1593 | if (!option) { |
| 1594 | return self; |
| 1595 | } |
| 1596 | |
| 1597 | const options = _.flatten(arguments); |
| 1598 | |
| 1599 | for (const option of options) { |
| 1600 | scope = null; |
| 1601 | scopeName = null; |
| 1602 | |
| 1603 | if (_.isPlainObject(option)) { |
| 1604 | if (option.method) { |
| 1605 | if (Array.isArray(option.method) && !!self.options.scopes[option.method[0]]) { |
| 1606 | scopeName = option.method[0]; |
| 1607 | scope = self.options.scopes[scopeName].apply(self, option.method.slice(1)); |
| 1608 | } |
| 1609 | else if (self.options.scopes[option.method]) { |
| 1610 | scopeName = option.method; |
| 1611 | scope = self.options.scopes[scopeName].apply(self); |
| 1612 | } |
| 1613 | } else { |
| 1614 | scope = option; |
| 1615 | } |
| 1616 | } else if (option === 'defaultScope' && _.isPlainObject(self.options.defaultScope)) { |
| 1617 | scope = self.options.defaultScope; |
| 1618 | } else { |
| 1619 | scopeName = option; |
| 1620 | scope = self.options.scopes[scopeName]; |
| 1621 | if (typeof scope === 'function') { |
| 1622 | scope = scope(); |
| 1623 | } |
| 1624 | } |
| 1625 | |
| 1626 | if (scope) { |
| 1627 | this._conformIncludes(scope, this); |
| 1628 | // clone scope so it doesn't get modified |
| 1629 | this._assignOptions(self._scope, Utils.cloneDeep(scope)); |
| 1630 | self._scopeNames.push(scopeName ? scopeName : 'defaultScope'); |
| 1631 | } else { |
| 1632 | throw new sequelizeErrors.SequelizeScopeError(`Invalid scope ${scopeName} called.`); |
| 1633 | } |
| 1634 | } |
| 1635 | |
| 1636 | return self; |
| 1637 | } |
| 1638 | |
| 1639 | /** |