All files / src/model scope-registry.ts

100% Statements 66/66
97.18% Branches 69/71
100% Functions 19/19
100% Lines 65/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234        132x                                                       132x 1584x         132x   5x     132x 23x   132x 7290x 7227x   63x 37x   26x 3x   23x 23x     132x 1530x     5x 5x 5x         132x           14562x 7290x   7272x 1x   7271x 1530x   5741x                                                       1295x 1295x 1295x                         9370x 9370x 9370x 14596x 14562x     9370x                     75x 51x 44x                     9316x                   2x                         1x                   51x 1x   50x 34x   16x 15x   1x       34x 3x   31x 31x 4x   27x 1x       26x       15x     15x 15x 15x 2x   13x      
import { SqlExpression } from '../expressions/methods.ts';
import { Op } from '../expressions/op.ts';
import { ValuesWriter } from './values-writer.ts';
 
const writer = new ValuesWriter();
 
/**
 * Find options stored in a scope (`where`, `attributes`, `order`, `limit`, ...).
 *
 * @example
 * ```ts
 * const scope: ScopeOptions = { where: { active: true }, order: [['createdAt', 'DESC']], limit: 100 };
 * User.init({ name: DataTypes.STRING }, { sequelize, defaultScope: scope });
 * ```
 */
export type ScopeOptions = Readonly<Record<string, unknown>>;
 
/** Scope definition: options, or a function of arguments returning options. */
export type ScopeDefinition = ScopeOptions | ((...args: never[]) => ScopeOptions);
 
/** Scope selector for `Model.scope()`: a name, `{ method: [name, ...args] }`, or inline options. */
export type ScopeSelector = string | ScopeMethodSelector | ScopeOptions | null;
 
/** `{ method: [name, ...args] }` — calls a function scope with arguments. */
export type ScopeMethodSelector = Readonly<{
  /** Scope function name, or `[name, ...args]`. */
  method: string | readonly [string, ...unknown[]];
}>;
 
/** `whereMergeStrategy` model option: overwrite same keys (v6 default) or combine with `Op.and`. */
export type WhereMergeStrategy = 'overwrite' | 'and';
 
const isPlainObject = (value: unknown): value is Readonly<Record<string | symbol, unknown>> =>
  typeof value === 'object' &&
  value !== null &&
  !Array.isArray(value) &&
  !(value instanceof SqlExpression);
 
const union = (left: readonly unknown[], right: readonly unknown[]): readonly unknown[] => [
  ...left,
  ...right.filter((item) => !left.includes(item)),
];
 
const asCondition = (value: unknown): unknown =>
  value instanceof SqlExpression ? { [Op.and]: value } : value;
 
const mergeWhere = (left: unknown, right: unknown, strategy: WhereMergeStrategy): unknown => {
  if (left === undefined) {
    return right;
  }
  if (right === undefined) {
    return left;
  }
  if (strategy === 'and') {
    return { [Op.and]: [left, right] };
  }
  const source = asCondition(right);
  return isPlainObject(left) && isPlainObject(source) ? { ...left, ...source } : source;
};
 
const mergeAttributes = (left: unknown, right: unknown): unknown =>
  isPlainObject(left) && isPlainObject(right)
    ? Object.fromEntries(
        [...new Set([...Object.keys(left), ...Object.keys(right)])].map((key) => {
          const a = left[key];
          const b = right[key];
          return [key, Array.isArray(a) && Array.isArray(b) ? union(a, b) : (b ?? a)];
        }),
      )
    : (right ?? left);
 
const mergeValue = (
  key: string,
  left: unknown,
  right: unknown,
  strategy: WhereMergeStrategy,
): unknown => {
  if (key === 'where' || key === 'having') {
    return mergeWhere(left, right, strategy);
  }
  if (Array.isArray(left) && Array.isArray(right)) {
    return union(left, right);
  }
  if (key === 'attributes') {
    return mergeAttributes(left, right);
  }
  return right === undefined ? left : right;
};
 
/**
 * Scopes of a model (default scope, named scopes, `whereMergeStrategy`) and the Sequelize v6
 * option merging rules used to apply them. Immutable: {@link ScopeRegistry.with} returns a new registry.
 */
export class ScopeRegistry {
  /** Default scope (`{}` when none). */
  readonly defaultScope: ScopeOptions;
  /** Named scopes. */
  readonly scopes: ReadonlyMap<string, ScopeDefinition>;
  /** How `where` / `having` of merged options combine. */
  readonly whereMergeStrategy: WhereMergeStrategy;
 
  /**
   * @param defaultScope - Default scope of the model.
   * @param scopes - Named scopes.
   * @param whereMergeStrategy - `'overwrite'` (default) or `'and'`.
   */
  constructor(
    defaultScope: ScopeOptions | undefined,
    scopes:
      | Readonly<Record<string, ScopeDefinition>>
      | ReadonlyMap<string, ScopeDefinition>
      | undefined,
    whereMergeStrategy: WhereMergeStrategy | undefined,
  ) {
    this.defaultScope = defaultScope ?? {};
    this.scopes = scopes instanceof Map ? scopes : new Map(Object.entries(scopes ?? {}));
    this.whereMergeStrategy = whereMergeStrategy ?? 'overwrite';
  }
 
  /**
   * Merges find options like Sequelize v6 `_assignOptions`: `where` / `having` keys of `right`
   * overwrite `left` (or are AND-ed with `whereMergeStrategy: 'and'`), arrays are unioned, other
   * keys of `right` win.
   *
   * @param left - Base options.
   * @param right - Options applied on top.
   * @returns Merged options.
   */
  merge(left: ScopeOptions, right: ScopeOptions): ScopeOptions {
    const strategy = this.whereMergeStrategy;
    const merged: Record<string, unknown> = {};
    for (const key of [...Object.keys(left), ...Object.keys(right)]) {
      if (!Object.hasOwn(merged, key)) {
        writer.set(merged, key, mergeValue(key, left[key], right[key], strategy));
      }
    }
    return merged;
  }
 
  /**
   * Resolves and merges the selected scopes in order (later scopes win).
   *
   * @param selectors - Scope names, `{ method: [name, ...args] }`, inline options or `null`.
   * @returns Merged scope options.
   * @throws Error for unknown scopes.
   */
  resolve(selectors: readonly ScopeSelector[]): ScopeOptions {
    return selectors
      .map((selector) => this.#resolveOne(selector))
      .reduce<ScopeOptions>((merged, scope) => this.merge(merged, scope), {});
  }
 
  /**
   * Applies a resolved scope to query options; the query options win (Sequelize v6 `_injectScope`).
   *
   * @param scope - Resolved scope.
   * @param options - Query options.
   * @returns Merged options.
   */
  inject<T extends ScopeOptions>(scope: ScopeOptions, options: T): T {
    return this.merge(scope, options) as T;
  }
 
  /**
   * Whether a scope with this name exists (`'defaultScope'`: whether it is not empty).
   *
   * @param name - Scope name.
   * @returns True when defined.
   */
  has(name: string): boolean {
    return name === 'defaultScope'
      ? Object.keys(this.defaultScope).length > 0
      : this.scopes.has(name);
  }
 
  /**
   * Registry with a scope added or replaced (`'defaultScope'` replaces the default scope).
   *
   * @param name - Scope name.
   * @param scope - Options or a function returning options.
   * @returns New registry.
   */
  with(name: string, scope: ScopeDefinition): ScopeRegistry {
    return name === 'defaultScope'
      ? new ScopeRegistry(scope as ScopeOptions, this.scopes, this.whereMergeStrategy)
      : new ScopeRegistry(
          this.defaultScope,
          new Map([...this.scopes, [name, scope]]),
          this.whereMergeStrategy,
        );
  }
 
  #resolveOne(selector: ScopeSelector): ScopeOptions {
    if (selector === null) {
      return {};
    }
    if (typeof selector === 'string') {
      return this.#resolveNamed(selector);
    }
    if ('method' in selector) {
      return this.#resolveMethod(selector as ScopeMethodSelector);
    }
    return selector;
  }
 
  #resolveNamed(selector: string): ScopeOptions {
    if (selector === 'defaultScope') {
      return this.defaultScope;
    }
    const scope = this.scopes.get(selector);
    if (scope === undefined) {
      throw new Error(`Invalid scope ${selector} called.`);
    }
    if (typeof scope === 'function') {
      throw new Error(
        `Scope "${selector}" is a function; use { method: ['${selector}', ...args] }`,
      );
    }
    return scope;
  }
 
  #resolveMethod(selector: ScopeMethodSelector): ScopeOptions {
    const method: readonly unknown[] = Array.isArray(selector.method)
      ? selector.method
      : [selector.method];
    const [name = '', ...args] = method as readonly string[];
    const scope = this.scopes.get(name);
    if (typeof scope !== 'function') {
      throw new Error(`Invalid scope ${name} called.`);
    }
    return (scope as (...scopeArgs: unknown[]) => ScopeOptions)(...args);
  }
}