Decorators

@system-inc/base-foundation · 515c140 · 25 symbols

Injects an OrmDatabase.

With no argument, resolution is module-aware: the database is the one the injecting class's declared module resolves to (its databaseName or the worker's database registration modifier). Membership is declared with @Injectable(SomeModuleKey) or any other injectable-family decorator; an undeclared class resolves to the default database — a uniform contract in every worker. Registration in module settings never routes injections (boot validation rejects a non-default-database module's class that forgot to declare). Pass a DatabaseBinding or a TypedInjectionKey whose registered value names a data context to select one explicitly — an explicit token always wins.

InjectDatabase(token?: DatabaseBinding | TypedInjectionKey<unknown>): TypedParameterDecorator<OrmDatabase>
@Injectable()
export class ReportService {
    constructor(@InjectDatabase() private database: OrmDatabase) {}

    async count(): Promise<number> {
        return await this.database.getRepository(Order).count();
    }
}

View source ↗

Injects an OrmRepository bound to the given Entity.

The entity type flows through to the resolved OrmRepository<EntityType>, so the parameter's declared type is verified at lint time.

InjectRepository(entity: Constructor<EntityType>, token?: DatabaseBinding | TypedInjectionKey<unknown>): TypedParameterDecorator<OrmRepository<EntityType>>
  • entity

    The target entity for which you want to inject the repository.

  • token

    Optional database selector — pass a `DatabaseBinding` or a `TypedInjectionKey` whose registered value names the data context. If omitted, resolution is **module-aware**: the repository binds to the database the injecting class's **declared module** resolves to (its `databaseName` or the worker's `database` registration modifier). Membership is declared with `@Injectable(SomeModuleKey)` or any other injectable-family decorator; an undeclared class resolves to the default database — a uniform contract in every worker. Registration in module settings never routes injections (boot validation rejects a non-default-database module's class that forgot to declare). An explicit token always wins.

@Injectable()
export class BookService {
    constructor(
        @InjectRepository(Book) private books: OrmRepository<Book>,
    ) {}

    async get(id: string): Promise<Book | undefined> {
        return await this.books.findOne({ where: { id } });
    }
}

View source ↗

Marks an entity method to run after the entity has been deleted.

OrmAfterDelete(): PropertyDecorator
@OrmAfterDelete()
logDeletion(): void {
    console.log(`deleted ${this.id}`);
}

View source ↗

Marks an entity method to run after the entity has been inserted. The entity's changed-field set is reset before the listener runs.

OrmAfterInsert(): PropertyDecorator
@OrmAfterInsert()
logCreation(): void {
    console.log(`created ${this.id}`);
}

View source ↗

@OrmAfterLoad

decorator

Marks an entity method to run after the entity has been hydrated from a database row — useful for computing derived fields. The entity starts with a clean changed-field set.

OrmAfterLoad(): PropertyDecorator
@OrmAfterLoad()
computeDisplayName(): void {
    this.displayName = `${this.firstName} ${this.lastName}`;
}

View source ↗

Marks an entity method to run after the entity has been updated. The entity's changed-field set is reset before the listener runs.

OrmAfterUpdate(): PropertyDecorator
@OrmAfterUpdate()
invalidateCache(): void {
    this.cachedSummary = undefined;
}

View source ↗

Marks an entity method to run just before the entity is deleted.

OrmBeforeDelete(): PropertyDecorator
@OrmBeforeDelete()
assertDeletable(): void {
    if (this.locked) throw new Error('Cannot delete a locked row.');
}

View source ↗

Marks an entity method to run just before the entity is inserted — the last chance to normalize or fill fields that persist with the insert.

OrmBeforeInsert(): PropertyDecorator
@OrmBeforeInsert()
normalizeEmail(): void {
    this.email = this.email.trim().toLowerCase();
}

View source ↗

Marks an entity method to run just before the entity is updated. Fields changed here are persisted with the update.

OrmBeforeUpdate(): PropertyDecorator
@OrmBeforeUpdate()
bumpRevision(): void {
    this.revision += 1;
}

View source ↗

@OrmColumn

decorator

Maps a property to a database column of the given kind.

The property must use the declare keyword — columns are backed by tracking accessors installed at construction time, so entity instances record their own changed fields for minimal partial updates.

Mode-bearing kinds (bigint, decimal, datetime) require an explicit mode choosing the JavaScript representation — see OrmColumnType.

OrmColumn(kind: OrmColumnType, options?: OrmColumnOptions<T>): PropertyDecorator
  • kind

    The column type and its type-specific options.

  • options

    Column options such as `nullable`, `unique`, or `default`.

@OrmColumn({ kind: 'varchar', length: 255 })
declare title: string;

@OrmColumn({ kind: 'varchar', length: 13 }, { unique: true })
declare isbn: string;

@OrmColumn({ kind: 'integer' }, { nullable: true })
declare pages: number | null;

View source ↗

Convenience decorator to add an index on a single column. Can be used with or without a custom name.

OrmColumnIndex(name?: string): PropertyDecorator
  • name

    Optional custom name for the index. If not provided, generates: idx_<tableName>_<propertyName>

class User {
  @OrmColumn({ kind: 'varchar', length: 36 })
  @OrmColumnIndex() // Auto-generates: idx_user_accountId
  declare accountId: string;

  @OrmColumn({ kind: 'varchar', length: 100 })
  @OrmColumnIndex('idx_user_email') // Custom name
  declare email: string;
}

View source ↗

Convenience decorator to add a unique constraint on a single column. Can be used with or without a custom name.

OrmColumnUnique(name?: string): PropertyDecorator
  • name

    Optional custom name for the unique constraint. If not provided, generates: unq_<tableName>_<propertyName>

class User {
  @OrmColumn({ kind: 'varchar', length: 100 })
  @OrmColumnUnique() // Auto-generates: unq_user_email
  declare email: string;

  @OrmColumn({ kind: 'varchar', length: 50 })
  @OrmColumnUnique('unq_username') // Custom name
  declare username: string;
}

View source ↗

Convenience decorator to add a unique index on a single column. This is different from OrmColumnUnique which creates a unique constraint. Can be used with or without a custom name.

OrmColumnUniqueIndex(name?: string): PropertyDecorator
  • name

    Optional custom name for the unique index. If not provided, generates: unq_idx_<tableName>_<propertyName>

class User {
  @OrmColumn({ kind: 'varchar', length: 100 })
  @OrmColumnUniqueIndex() // Auto-generates: unq_idx_user_email
  declare email: string;

  @OrmColumn({ kind: 'varchar', length: 50 })
  @OrmColumnUniqueIndex('unq_idx_custom_username') // Custom name
  declare username: string;
}

View source ↗

Marks a property as the row's creation timestamp, set automatically on insert and immutable afterwards — upserts never overwrite it.

OrmCreateDateColumn(options?: OrmColumnOptions): PropertyDecorator
  • options

    Column options.

@OrmCreateDateColumn()
declare createdAt: Date;

View source ↗

Specifies a join column for a relation. Used with @OrmManyToOne and @OrmOneToOne relations to configure the foreign key column.

OrmJoinColumn(options?: OrmJoinColumnOptions): PropertyDecorator
class Post {
  @OrmManyToOne(() => User)
  @OrmJoinColumn({ name: 'author_id', nullable: false })
  author: User;
}

View source ↗

@OrmManyToOne

decorator

Defines a many-to-one relation. Multiple instances of this entity can reference one instance of the target entity.

OrmManyToOne(target: () => Constructor<TargetType>, options?: OrmManyToOneOptions<TargetType>): PropertyDecorator
class Post {
  @OrmManyToOne(() => User, { joinColumn: 'authorId' })
  author: User;
}

View source ↗

@OrmOneToMany

decorator

Defines a one-to-many relation. One instance of this entity can be referenced by multiple instances of the target entity.

OrmOneToMany(target: () => Constructor<TargetType>, options: OrmOneToManyOptions<TargetType>): PropertyDecorator
class User {
  @OrmOneToMany(() => Post, { inverseSide: 'author' })
  posts: Post[];
}

View source ↗

@OrmOneToOne

decorator

Defines a one-to-one relation. One instance of this entity references exactly one instance of the target entity.

OrmOneToOne(target: () => Constructor<TargetType>, options?: OrmOneToOneOptions<TargetType>): PropertyDecorator
class User {
  @OrmOneToOne(() => Profile, { joinColumn: 'profileId' })
  profile: Profile;
}

View source ↗

Marks a property as the table's auto-generated primary key.

With 'uuid' the key is a generated UUID string; with 'serial' it is an auto-incremented integer (optionally sized).

OrmPrimaryAutoColumn(strategy: "uuid"): PropertyDecorator
  • strategy

    How the key is generated: `'uuid'` or `'serial'`.

OrmPrimaryAutoColumn(strategy: "serial", size?: OrmIntegerSizeType): PropertyDecorator
  • strategy

    The `'serial'` strategy.

  • size

    The integer size of the column.

@OrmPrimaryAutoColumn('uuid')
declare id: string;

View source ↗

Declares the table's composite primary key on the entity class.

A table's primary key is declared exactly once: either a single column (@OrmPrimaryAutoColumn or a column with primaryKey: true) or this decorator listing the key columns. Order matters — it defines the backing index, so list the hot lookup path first. Conflicting declarations throw at class definition time.

OrmPrimaryKey(columns: string[], options?: OrmPrimaryKeyOptions): (ctor: T) => void
  • columns

    The property names composing the key, in index order.

  • options

    Additional primary key options.

// A junction table with a composite key
@OrmTable('book_genres')
@OrmPrimaryKey(['bookId', 'genreId'])
export class BookGenre extends OrmTrackingEntity {
    @OrmColumn({ kind: 'varchar', length: 36 })
    declare bookId: string;

    @OrmColumn({ kind: 'varchar', length: 36 })
    declare genreId: string;
}

View source ↗

@OrmTable

decorator

Marks a class as a database entity backed by a table.

Register the entity in a module's (or the worker's) orm.entities; the schema builder turns its decorated columns into the table definition, and repositories for it are injected with @InjectRepository. Entities extend OrmTrackingEntity (or OrmBaseEntity/OrmMutableBaseEntity) so instances track their own changed fields.

OrmTable(name?: string, options?: OrmTableOptions): (ctor: T) => void
  • name

    The table name. Defaults to the class name when omitted.

  • options

    Additional table options.

@OrmTable('books')
export class Book extends OrmTrackingEntity {
    @OrmPrimaryAutoColumn('uuid')
    declare id: string;

    @OrmColumn({ kind: 'varchar', length: 255 })
    declare title: string;

    @OrmCreateDateColumn()
    declare createdAt: Date;
}

View source ↗

Adds an index over the given columns to the entity's table, with an auto-generated name.

OrmTableIndex(columns: OrmIndexColumn[], options?: OrmTableIndexOptions): (ctor: T) => void
  • columns

    The columns to include in the index.

  • options

    Additional index options.

OrmTableIndex(name: string, columns: OrmIndexColumn[], options?: OrmTableIndexOptions): (ctor: T) => void
  • name

    Custom name for the index.

  • columns

    The columns to include in the index.

  • options

    Additional index options.

@OrmTable('orders')
@OrmTableIndex(['orderDate'])
export class Order extends OrmTrackingEntity { ... }

View source ↗

Decorator to add a unique constraint to a table with auto-generated name.

OrmTableUnique(columns: string[]): (ctor: T) => void
  • columns

    The columns to include in the unique constraint

OrmTableUnique(name: string, columns: string[]): (ctor: T) => void
  • name

    Custom name for the unique constraint

  • columns

    The columns to include in the unique constraint

// Auto-generated name: uc_user_email_username
@OrmTableUnique(['email', 'username'])
class User {
  // ...
}

View source ↗

Adds a unique index over the given columns to the entity's table, with an auto-generated name.

OrmTableUniqueIndex(columns: string[], options?: OrmTableIndexOptions): (ctor: T) => void
  • columns

    The columns to include in the unique index.

  • options

    Additional index options.

OrmTableUniqueIndex(name: string, columns: string[], options?: OrmTableIndexOptions): (ctor: T) => void
  • name

    Custom name for the unique index.

  • columns

    The columns to include in the unique index.

  • options

    Additional index options.

@OrmTable('members')
@OrmTableUniqueIndex(['organizationId', 'accountId'])
export class Member extends OrmTrackingEntity { ... }

View source ↗

Marks a property as the row's last-update timestamp, initialized to the creation time on insert and refreshed automatically on every update.

The column is non-nullable by default: a row that has never been updated is one where updatedAt equals createdAt, not one where it is null.

OrmUpdateDateColumn(options?: OrmColumnOptions): PropertyDecorator
  • options

    Column options.

@OrmUpdateDateColumn()
declare updatedAt: Date;

View source ↗