* Apply a scope created in `define` to the model. * * @example <caption>how to create scopes</caption> * const Model = sequelize.define('model', attributes, { * defaultScope: { * where: { * username: 'dan' * }, * limit: 12 * }, * scopes: { *
(option)
| 1529 | * @returns {Model} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope. |
| 1530 | */ |
| 1531 | static scope(option) { |
| 1532 | const self = class extends this {}; |
| 1533 | let scope; |
| 1534 | let scopeName; |
| 1535 | |
| 1536 | Object.defineProperty(self, class="st">'name', { value: this.name }); |
| 1537 | |
| 1538 | self._scope = {}; |
| 1539 | self._scopeNames = []; |
| 1540 | self.scoped = true; |
| 1541 | |
| 1542 | if (!option) { |
| 1543 | return self; |
| 1544 | } |
| 1545 | |
| 1546 | const options = _.flatten(arguments); |
| 1547 | |
| 1548 | for (const option of options) { |
| 1549 | scope = null; |
| 1550 | scopeName = null; |
| 1551 | |
| 1552 | if (_.isPlainObject(option)) { |
| 1553 | if (option.method) { |
| 1554 | if (Array.isArray(option.method) && !!self.options.scopes[option.method[0]]) { |
| 1555 | scopeName = option.method[0]; |
| 1556 | scope = self.options.scopes[scopeName].apply(self, option.method.slice(1)); |
| 1557 | } |
| 1558 | else if (self.options.scopes[option.method]) { |
| 1559 | scopeName = option.method; |
| 1560 | scope = self.options.scopes[scopeName].apply(self); |
| 1561 | } |
| 1562 | } else { |
| 1563 | scope = option; |
| 1564 | } |
| 1565 | } else if (option === class="st">'defaultScope' && _.isPlainObject(self.options.defaultScope)) { |
| 1566 | scope = self.options.defaultScope; |
| 1567 | } else { |
| 1568 | scopeName = option; |
| 1569 | scope = self.options.scopes[scopeName]; |
| 1570 | if (typeof scope === class="st">'function') { |
| 1571 | scope = scope(); |
| 1572 | } |
| 1573 | } |
| 1574 | |
| 1575 | if (scope) { |
| 1576 | this._conformIncludes(scope, this); |
| 1577 | class="cm">// clone scope so it doesn't get modified |
| 1578 | this._assignOptions(self._scope, Utils.cloneDeep(scope)); |
| 1579 | self._scopeNames.push(scopeName ? scopeName : class="st">'defaultScope'); |
| 1580 | } else { |
| 1581 | throw new sequelizeErrors.SequelizeScopeError(`Invalid scope ${scopeName} called.`); |
| 1582 | } |
| 1583 | } |
| 1584 | |
| 1585 | return self; |
| 1586 | } |
| 1587 | |
| 1588 | /** |