All files / src/model model-accessors.ts

90% Statements 9/10
50% Branches 1/2
100% Functions 8/8
90% Lines 9/10

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                                            1811x 7589x   5273x       277x     27x                         627x     627x       199x         3x                    
import type { ModelDefinition } from './model-definition.ts';
 
type AttributeHost = Readonly<{
  get: (name: string) => unknown;
  set: (name: string, value: unknown) => unknown;
}>;
 
type AssociationHost = Readonly<{ dataValues: Record<string, unknown> }>;
 
/**
 * Installs `instance.<attribute>` and `instance.<alias>` accessors on model prototypes.
 *
 * @internal
 */
export class ModelAccessors {
  /**
   * Defines `instance.<attribute>` getters / setters on the model prototype (once per attribute).
   *
   * @param prototype - Model prototype.
   * @param definition - Model definition.
   */
  defineAttributes(prototype: object, definition: ModelDefinition): void {
    [...definition.attributes.keys()]
      .filter((name) => !Object.prototype.hasOwnProperty.call(prototype, name))
      .forEach((name) =>
        Object.defineProperty(prototype, name, {
          configurable: true,
          enumerable: false,
          get(this: AttributeHost) {
            return this.get(name);
          },
          set(this: AttributeHost, value: unknown) {
            this.set(name, value);
          },
        }),
      );
  }
 
  /**
   * Defines `instance.<alias>` for an association, holding included / nested instances.
   *
   * @param prototype - Model prototype.
   * @param alias - Association alias.
   */
  defineAssociation(prototype: object, alias: string): void {
    Iif (Object.prototype.hasOwnProperty.call(prototype, alias)) {
      return;
    }
    Object.defineProperty(prototype, alias, {
      configurable: true,
      enumerable: false,
      get(this: AssociationHost) {
        return this.dataValues[alias];
      },
      // Like v6, a value assigned by the caller is a plain property of the instance and not part of its
      // values, so `get({ plain: true })` / `toJSON()` do not follow it (a cycle would never end).
      set(this: AssociationHost, value: unknown) {
        Object.defineProperty(this, alias, {
          value,
          writable: true,
          enumerable: true,
          configurable: true,
        });
      },
    });
  }
}