All files / src/decorators model-metadata.ts

100% Statements 23/23
100% Branches 10/10
100% Functions 10/10
100% Lines 18/18

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                                                                                                  131x                   1064x                   131x             178x 178x 178x               70x 70x 988x   988x       988x     988x 1976x         131x       78x 176x           131x                         131x  
import type { AssociationOptions, ThroughOptions } from '../associations/types.ts';
import type { IndexOptions } from '../ddl/ddl-generator.ts';
import type { HookType } from '../hooks/hooks.ts';
import type { AttributeOptions } from '../model/attribute-options.ts';
import type { AnyModel, InitOptions, ModelStatic } from '../model/options.ts';
import type { ScopeDefinition, ScopeOptions } from '../model/scope-registry.ts';
import type { DecoratorTarget } from './decorator-signature.ts';
 
/** Lazily resolved model class, so decorators can refer to classes defined later in the file. */
export type ModelGetter = () => ModelStatic<AnyModel>;
 
/**
 * Table options of `@Table`: the `Model.init` options without the `sequelize` instance.
 *
 * @example
 * ```ts
 * const options: TableOptions = { tableName: 'users', schema: 'app', paranoid: true, timestamps: true };
 * ```
 */
export type TableOptions = Omit<InitOptions, 'sequelize'>;
 
/** Named scopes given to `@Scopes`. */
export type ScopesInput = Readonly<Record<string, ScopeDefinition>>;
 
/** Association collected from `@HasOne`, `@HasMany`, `@BelongsTo` or `@BelongsToMany`. */
export type AssociationSpec = Readonly<{
  kind: 'hasOne' | 'hasMany' | 'belongsTo' | 'belongsToMany';
  key: string;
  target: ModelGetter;
  options: AssociationOptions;
  through?: string | ModelGetter | ThroughOptions;
}>;
 
/** Index collected from `@Index` on an attribute. */
export type IndexSpec = Readonly<{ key: string; options: IndexOptions }>;
 
/** Everything the decorators collected for one class. */
export type ModelMetadata = {
  table: TableOptions;
  defaultScope?: ScopeOptions | (() => ScopeOptions);
  scopes?: ScopesInput | (() => ScopesInput);
  columns: Record<string, Partial<AttributeOptions>>;
  timestamps: Partial<Record<'createdAt' | 'updatedAt' | 'deletedAt', string>>;
  foreignKeys: Record<string, ModelGetter>;
  indexes: IndexSpec[];
  associations: AssociationSpec[];
  hooks: { type: HookType; key: string }[];
};
 
const empty = (): ModelMetadata => ({
  table: {},
  columns: {},
  timestamps: {},
  foreignKeys: {},
  indexes: [],
  associations: [],
  hooks: [],
});
 
const symbolMetadata = (): symbol => (Symbol as unknown as { metadata: symbol }).metadata;
 
/**
 * Metadata that decorators collect, kept outside the decorated classes (no `reflect-metadata`).
 * Decorated classes are looked up by the class itself (legacy decorators) or by their TC39
 * `Symbol.metadata` bag; base classes contribute first.
 *
 * @internal
 */
export class MetadataStore {
  readonly #entries = new WeakMap<object, ModelMetadata>();
 
  /**
   * @param target - What the running decorator decorates.
   * @returns The metadata bag of its class, created on first use.
   */
  of(target: DecoratorTarget): ModelMetadata {
    const found = this.#entries.get(target.owner) ?? empty();
    this.#entries.set(target.owner, found);
    return found;
  }
 
  /**
   * @param model - Decorated class.
   * @returns Metadata of the class merged with its base classes' (derived classes win).
   */
  collect(model: object): ModelMetadata {
    const chain: object[] = [];
    for (let link: object | null = model; link !== null; link = Object.getPrototypeOf(link)) {
      chain.unshift(link);
    }
    return chain.flatMap((link) => this.#bags(link)).reduce(merge, empty());
  }
 
  #bags(link: object): ModelMetadata[] {
    const bag = Object.hasOwn(link, symbolMetadata())
      ? (link as Record<symbol, object>)[symbolMetadata()]
      : undefined;
    return [this.#entries.get(link), bag === undefined ? undefined : this.#entries.get(bag)].filter(
      (entry): entry is ModelMetadata => entry !== undefined,
    );
  }
}
 
const mergeColumns = (
  base: ModelMetadata['columns'],
  next: ModelMetadata['columns'],
): ModelMetadata['columns'] =>
  Object.fromEntries(
    [...Object.keys(base), ...Object.keys(next)].map((key) => [
      key,
      { ...base[key], ...next[key] },
    ]),
  );
 
const merge = (base: ModelMetadata, next: ModelMetadata): ModelMetadata => ({
  table: { ...base.table, ...next.table },
  defaultScope: next.defaultScope ?? base.defaultScope,
  scopes: next.scopes ?? base.scopes,
  columns: mergeColumns(base.columns, next.columns),
  timestamps: { ...base.timestamps, ...next.timestamps },
  foreignKeys: { ...base.foreignKeys, ...next.foreignKeys },
  indexes: [...base.indexes, ...next.indexes],
  associations: [...base.associations, ...next.associations],
  hooks: [...base.hooks, ...next.hooks],
});
 
/** @internal Shared metadata store of all decorators. */
export const metadata = new MetadataStore();