All files / src/sequelize model-manager.ts

40% Statements 4/10
100% Branches 0/0
57.14% Functions 4/7
44.44% Lines 4/9

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                                  799x         2x                                                     1x                   1x      
import type { AnyModel, ModelStatic } from '../model/options.ts';
 
/**
 * Registry of the models of a `Sequelize` instance (Sequelize v6 `sequelize.modelManager`), a view on `sequelize.models`.
 *
 * @example
 * ```ts
 * sequelize.modelManager.removeModel(sequelize.model('Temp'));
 * ```
 */
export class ModelManager {
  readonly #models: Record<string, ModelStatic<AnyModel>>;
 
  /**
   * @param models - The `sequelize.models` object this manager reads and writes.
   */
  constructor(models: Record<string, ModelStatic<AnyModel>>) {
    this.#models = models;
  }
 
  /** Defined models in definition order; assigning a list replaces them (v6 tests reset the manager with `models = []`). */
  get models(): ModelStatic<AnyModel>[] {
    return Object.values(this.#models);
  }
 
  set models(list: readonly ModelStatic<AnyModel>[]) {
    for (const name of Object.keys(this.#models)) {
      delete this.#models[name];
    }
    list.forEach((model) => this.addModel(model));
  }
 
  /**
   * Adds a model under its name.
   *
   * @param model - Model class.
   * @returns The model.
   */
  addModel<M extends ModelStatic<AnyModel>>(model: M): M {
    this.#models[model.name] = model;
    return model;
  }
 
  /**
   * Removes a model from `sequelize.models`; its table is not touched.
   *
   * @param model - Model class.
   */
  removeModel(model: ModelStatic<AnyModel>): void {
    delete this.#models[model.name];
  }
 
  /**
   * Finds a model by name.
   *
   * @param against - Model name.
   * @returns The model, or `undefined`.
   */
  getModel(against: string): ModelStatic<AnyModel> | undefined {
    return this.#models[against];
  }
}