All files / src/decorators model-decorators.ts

100% Statements 8/8
100% Branches 0/0
100% Functions 1/1
100% Lines 8/8

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                              131x 131x             10x 25x 25x   9x 24x 18x          
import type { AnyModel, ModelStatic } from '../model/options.ts';
import type { RuntimeOwner } from '../model/runtime.ts';
import { AssociationApplier } from './association-applier.ts';
import { InitArguments } from './init-arguments.ts';
import { metadata } from './model-metadata.ts';
 
type Model = ModelStatic<AnyModel>;
 
/**
 * Registers decorated model classes: initializes every class with `Model.init`, then adds the
 * declared associations, so classes may refer to each other regardless of their order.
 *
 * @internal
 */
export class ModelDecorators {
  readonly #init = new InitArguments();
  readonly #associations = new AssociationApplier();
 
  /**
   * @param sequelize - Instance the models are registered with.
   * @param models - Decorated model classes.
   */
  register(sequelize: RuntimeOwner, models: readonly Model[]): void {
    for (const model of models) {
      const meta = metadata.collect(model);
      model.init(this.#init.attributes(model, meta), this.#init.options(model, meta, sequelize));
    }
    for (const model of models) {
      for (const spec of metadata.collect(model).associations) {
        this.#associations.apply(model, spec);
      }
    }
  }
}