All files / src/decorators init-arguments.ts

100% Statements 29/29
96.15% Branches 25/26
100% Functions 6/6
100% Lines 29/29

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                                              25x 60x 1x     24x                   24x 24x 24x                       24x 24x 24x 7x 7x 6x 6x 6x 3x     1x     24x       24x 20x   4x 4x 2x   4x 5x 6x 5x   4x       24x                
import type { HookFunction, HookType, HooksOption } from '../hooks/hooks.ts';
import type { ModelAttributes } from '../model/model-definition.ts';
import type { AnyModel, InitOptions, ModelStatic } from '../model/options.ts';
import type { RuntimeOwner } from '../model/runtime.ts';
import type { IndexOptions } from '../ddl/ddl-generator.ts';
import type { ModelMetadata } from './model-metadata.ts';
 
type Model = ModelStatic<AnyModel>;
 
/**
 * Turns the metadata collected for a class into the arguments of `Model.init`, so a decorated
 * model is initialized exactly like a hand-written `init` call.
 *
 * @internal
 */
export class InitArguments {
  /**
   * @param model - Decorated class.
   * @param meta - Metadata collected for it.
   * @returns Attributes for `Model.init`.
   * @throws Error when an attribute has no type.
   */
  attributes(model: Model, meta: ModelMetadata): ModelAttributes {
    for (const [key, column] of Object.entries(meta.columns)) {
      if (column.type === undefined) {
        throw new Error(`${model.name}.${key} has no type: use @Column(DataTypes.<TYPE>).`);
      }
    }
    return meta.columns as ModelAttributes;
  }
 
  /**
   * @param model - Decorated class.
   * @param meta - Metadata collected for it.
   * @param sequelize - Owning instance.
   * @returns Options for `Model.init`.
   */
  options(model: Model, meta: ModelMetadata, sequelize: RuntimeOwner): InitOptions {
    const { table, timestamps } = meta;
    const paranoid = timestamps.deletedAt === undefined ? {} : { paranoid: true };
    return {
      ...paranoid,
      ...table,
      ...timestamps,
      ...this.#indexes(meta),
      ...this.#hooks(model, meta),
      ...this.#scopes(meta),
      sequelize,
    };
  }
 
  #indexes({ table, indexes }: ModelMetadata): Pick<InitOptions, 'indexes'> {
    const named = new Map<string, IndexOptions>();
    const all: IndexOptions[] = [...(table.indexes ?? [])];
    for (const { key, options } of indexes) {
      const known = options.name === undefined ? undefined : named.get(options.name);
      if (known === undefined) {
        const created = { ...options, fields: [key] };
        all.push(created);
        if (options.name !== undefined) {
          named.set(options.name, created);
        }
      } else {
        (known.fields as string[]).push(key);
      }
    }
    return all.length === 0 ? {} : { indexes: all };
  }
 
  #hooks(model: Model, { table, hooks }: ModelMetadata): Pick<InitOptions, 'hooks'> {
    if (hooks.length === 0) {
      return {};
    }
    const merged: Partial<Record<HookType, HookFunction[]>> = {};
    for (const [type, value] of Object.entries(table.hooks ?? {})) {
      merged[type as HookType] = [value].flat() as HookFunction[];
    }
    for (const { type, key } of hooks) {
      const call = (...args: unknown[]): unknown =>
        (model as never as Record<string, (...a: unknown[]) => unknown>)[key]?.(...args);
      (merged[type] ??= []).push(call as HookFunction);
    }
    return { hooks: merged as HooksOption };
  }
 
  #scopes({ defaultScope, scopes }: ModelMetadata): Pick<InitOptions, 'defaultScope' | 'scopes'> {
    return {
      ...(defaultScope === undefined
        ? {}
        : { defaultScope: typeof defaultScope === 'function' ? defaultScope() : defaultScope }),
      ...(scopes === undefined ? {} : { scopes: typeof scopes === 'function' ? scopes() : scopes }),
    };
  }
}